clang  6.0.0
SemaTemplate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===//
11 
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.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/TypeVisitor.h"
21 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/Template.h"
32 #include "llvm/ADT/SmallBitVector.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 
36 #include <iterator>
37 using namespace clang;
38 using namespace sema;
39 
40 // Exported for use by Parser.
43  unsigned N) {
44  if (!N) return SourceRange();
45  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46 }
47 
48 namespace clang {
49 /// \brief [temp.constr.decl]p2: A template's associated constraints are
50 /// defined as a single constraint-expression derived from the introduced
51 /// constraint-expressions [ ... ].
52 ///
53 /// \param Params The template parameter list and optional requires-clause.
54 ///
55 /// \param FD The underlying templated function declaration for a function
56 /// template.
58  FunctionDecl *FD);
59 }
60 
62  FunctionDecl *FD) {
63  // FIXME: Concepts: collect additional introduced constraint-expressions
64  assert(!FD && "Cannot collect constraints from function declaration yet.");
65  return Params->getRequiresClause();
66 }
67 
68 /// \brief Determine whether the declaration found is acceptable as the name
69 /// of a template and, if so, return that template declaration. Otherwise,
70 /// returns NULL.
72  NamedDecl *Orig,
73  bool AllowFunctionTemplates) {
74  NamedDecl *D = Orig->getUnderlyingDecl();
75 
76  if (isa<TemplateDecl>(D)) {
77  if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
78  return nullptr;
79 
80  return Orig;
81  }
82 
83  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84  // C++ [temp.local]p1:
85  // Like normal (non-template) classes, class templates have an
86  // injected-class-name (Clause 9). The injected-class-name
87  // can be used with or without a template-argument-list. When
88  // it is used without a template-argument-list, it is
89  // equivalent to the injected-class-name followed by the
90  // template-parameters of the class template enclosed in
91  // <>. When it is used with a template-argument-list, it
92  // refers to the specified class template specialization,
93  // which could be the current specialization or another
94  // specialization.
95  if (Record->isInjectedClassName()) {
96  Record = cast<CXXRecordDecl>(Record->getDeclContext());
97  if (Record->getDescribedClassTemplate())
98  return Record->getDescribedClassTemplate();
99 
101  = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102  return Spec->getSpecializedTemplate();
103  }
104 
105  return nullptr;
106  }
107 
108  return nullptr;
109 }
110 
112  bool AllowFunctionTemplates) {
113  // The set of class templates we've already seen.
114  llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
115  LookupResult::Filter filter = R.makeFilter();
116  while (filter.hasNext()) {
117  NamedDecl *Orig = filter.next();
118  NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
119  AllowFunctionTemplates);
120  if (!Repl)
121  filter.erase();
122  else if (Repl != Orig) {
123 
124  // C++ [temp.local]p3:
125  // A lookup that finds an injected-class-name (10.2) can result in an
126  // ambiguity in certain cases (for example, if it is found in more than
127  // one base class). If all of the injected-class-names that are found
128  // refer to specializations of the same class template, and if the name
129  // is used as a template-name, the reference refers to the class
130  // template itself and not a specialization thereof, and is not
131  // ambiguous.
132  if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
133  if (!ClassTemplates.insert(ClassTmpl).second) {
134  filter.erase();
135  continue;
136  }
137 
138  // FIXME: we promote access to public here as a workaround to
139  // the fact that LookupResult doesn't let us remember that we
140  // found this template through a particular injected class name,
141  // which means we end up doing nasty things to the invariants.
142  // Pretending that access is public is *much* safer.
143  filter.replace(Repl, AS_public);
144  }
145  }
146  filter.done();
147 }
148 
150  bool AllowFunctionTemplates) {
151  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
152  if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
153  return true;
154 
155  return false;
156 }
157 
159  CXXScopeSpec &SS,
160  bool hasTemplateKeyword,
161  UnqualifiedId &Name,
162  ParsedType ObjectTypePtr,
163  bool EnteringContext,
164  TemplateTy &TemplateResult,
165  bool &MemberOfUnknownSpecialization) {
166  assert(getLangOpts().CPlusPlus && "No template names in C!");
167 
168  DeclarationName TName;
169  MemberOfUnknownSpecialization = false;
170 
171  switch (Name.getKind()) {
173  TName = DeclarationName(Name.Identifier);
174  break;
175 
177  TName = Context.DeclarationNames.getCXXOperatorName(
179  break;
180 
183  break;
184 
185  default:
186  return TNK_Non_template;
187  }
188 
189  QualType ObjectType = ObjectTypePtr.get();
190 
191  LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
192  LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193  MemberOfUnknownSpecialization);
194  if (R.empty()) return TNK_Non_template;
195  if (R.isAmbiguous()) {
196  // Suppress diagnostics; we'll redo this lookup later.
197  R.suppressDiagnostics();
198 
199  // FIXME: we might have ambiguous templates, in which case we
200  // should at least parse them properly!
201  return TNK_Non_template;
202  }
203 
204  TemplateName Template;
205  TemplateNameKind TemplateKind;
206 
207  unsigned ResultCount = R.end() - R.begin();
208  if (ResultCount > 1) {
209  // We assume that we'll preserve the qualifier from a function
210  // template name in other ways.
211  Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212  TemplateKind = TNK_Function_template;
213 
214  // We'll do this lookup again later.
215  R.suppressDiagnostics();
216  } else {
217  TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218 
219  if (SS.isSet() && !SS.isInvalid()) {
220  NestedNameSpecifier *Qualifier = SS.getScopeRep();
221  Template = Context.getQualifiedTemplateName(Qualifier,
222  hasTemplateKeyword, TD);
223  } else {
224  Template = TemplateName(TD);
225  }
226 
227  if (isa<FunctionTemplateDecl>(TD)) {
228  TemplateKind = TNK_Function_template;
229 
230  // We'll do this lookup again later.
231  R.suppressDiagnostics();
232  } else {
233  assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
234  isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235  isa<BuiltinTemplateDecl>(TD));
236  TemplateKind =
237  isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
238  }
239  }
240 
241  TemplateResult = TemplateTy::make(Template);
242  return TemplateKind;
243 }
244 
246  SourceLocation NameLoc,
247  ParsedTemplateTy *Template) {
248  CXXScopeSpec SS;
249  bool MemberOfUnknownSpecialization = false;
250 
251  // We could use redeclaration lookup here, but we don't need to: the
252  // syntactic form of a deduction guide is enough to identify it even
253  // if we can't look up the template name at all.
254  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255  LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256  /*EnteringContext*/false, MemberOfUnknownSpecialization);
257 
258  if (R.empty()) return false;
259  if (R.isAmbiguous()) {
260  // FIXME: Diagnose an ambiguity if we find at least one template.
262  return false;
263  }
264 
265  // We only treat template-names that name type templates as valid deduction
266  // guide names.
268  if (!TD || !getAsTypeTemplateDecl(TD))
269  return false;
270 
271  if (Template)
272  *Template = TemplateTy::make(TemplateName(TD));
273  return true;
274 }
275 
277  SourceLocation IILoc,
278  Scope *S,
279  const CXXScopeSpec *SS,
280  TemplateTy &SuggestedTemplate,
281  TemplateNameKind &SuggestedKind) {
282  // We can't recover unless there's a dependent scope specifier preceding the
283  // template name.
284  // FIXME: Typo correction?
285  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286  computeDeclContext(*SS))
287  return false;
288 
289  // The code is missing a 'template' keyword prior to the dependent template
290  // name.
292  Diag(IILoc, diag::err_template_kw_missing)
293  << Qualifier << II.getName()
294  << FixItHint::CreateInsertion(IILoc, "template ");
295  SuggestedTemplate
296  = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297  SuggestedKind = TNK_Dependent_template_name;
298  return true;
299 }
300 
302  Scope *S, CXXScopeSpec &SS,
303  QualType ObjectType,
304  bool EnteringContext,
305  bool &MemberOfUnknownSpecialization) {
306  // Determine where to perform name lookup
307  MemberOfUnknownSpecialization = false;
308  DeclContext *LookupCtx = nullptr;
309  bool isDependent = false;
310  if (!ObjectType.isNull()) {
311  // This nested-name-specifier occurs in a member access expression, e.g.,
312  // x->B::f, and we are looking into the type of the object.
313  assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314  LookupCtx = computeDeclContext(ObjectType);
315  isDependent = ObjectType->isDependentType();
316  assert((isDependent || !ObjectType->isIncompleteType() ||
317  ObjectType->castAs<TagType>()->isBeingDefined()) &&
318  "Caller should have completed object type");
319 
320  // Template names cannot appear inside an Objective-C class or object type.
321  if (ObjectType->isObjCObjectOrInterfaceType()) {
322  Found.clear();
323  return;
324  }
325  } else if (SS.isSet()) {
326  // This nested-name-specifier occurs after another nested-name-specifier,
327  // so long into the context associated with the prior nested-name-specifier.
328  LookupCtx = computeDeclContext(SS, EnteringContext);
329  isDependent = isDependentScopeSpecifier(SS);
330 
331  // The declaration context must be complete.
332  if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
333  return;
334  }
335 
336  bool ObjectTypeSearchedInScope = false;
337  bool AllowFunctionTemplatesInLookup = true;
338  if (LookupCtx) {
339  // Perform "qualified" name lookup into the declaration context we
340  // computed, which is either the type of the base of a member access
341  // expression or the declaration context associated with a prior
342  // nested-name-specifier.
343  LookupQualifiedName(Found, LookupCtx);
344  if (!ObjectType.isNull() && Found.empty()) {
345  // C++ [basic.lookup.classref]p1:
346  // In a class member access expression (5.2.5), if the . or -> token is
347  // immediately followed by an identifier followed by a <, the
348  // identifier must be looked up to determine whether the < is the
349  // beginning of a template argument list (14.2) or a less-than operator.
350  // The identifier is first looked up in the class of the object
351  // expression. If the identifier is not found, it is then looked up in
352  // the context of the entire postfix-expression and shall name a class
353  // or function template.
354  if (S) LookupName(Found, S);
355  ObjectTypeSearchedInScope = true;
356  AllowFunctionTemplatesInLookup = false;
357  }
358  } else if (isDependent && (!S || ObjectType.isNull())) {
359  // We cannot look into a dependent object type or nested nme
360  // specifier.
361  MemberOfUnknownSpecialization = true;
362  return;
363  } else {
364  // Perform unqualified name lookup in the current scope.
365  LookupName(Found, S);
366 
367  if (!ObjectType.isNull())
368  AllowFunctionTemplatesInLookup = false;
369  }
370 
371  if (Found.empty() && !isDependent) {
372  // If we did not find any names, attempt to correct any typos.
373  DeclarationName Name = Found.getLookupName();
374  Found.clear();
375  // Simple filter callback that, for keywords, only accepts the C++ *_cast
376  auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377  FilterCCC->WantTypeSpecifiers = false;
378  FilterCCC->WantExpressionKeywords = false;
379  FilterCCC->WantRemainingKeywords = false;
380  FilterCCC->WantCXXNamedCasts = true;
381  if (TypoCorrection Corrected = CorrectTypo(
382  Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383  std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
384  Found.setLookupName(Corrected.getCorrection());
385  if (auto *ND = Corrected.getFoundDecl())
386  Found.addDecl(ND);
387  FilterAcceptableTemplateNames(Found);
388  if (!Found.empty()) {
389  if (LookupCtx) {
390  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
392  Name.getAsString() == CorrectedStr;
393  diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394  << Name << LookupCtx << DroppedSpecifier
395  << SS.getRange());
396  } else {
397  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
398  }
399  }
400  } else {
401  Found.setLookupName(Name);
402  }
403  }
404 
405  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
406  if (Found.empty()) {
407  if (isDependent)
408  MemberOfUnknownSpecialization = true;
409  return;
410  }
411 
412  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
413  !getLangOpts().CPlusPlus11) {
414  // C++03 [basic.lookup.classref]p1:
415  // [...] If the lookup in the class of the object expression finds a
416  // template, the name is also looked up in the context of the entire
417  // postfix-expression and [...]
418  //
419  // Note: C++11 does not perform this second lookup.
420  LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421  LookupOrdinaryName);
422  LookupName(FoundOuter, S);
423  FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
424 
425  if (FoundOuter.empty()) {
426  // - if the name is not found, the name found in the class of the
427  // object expression is used, otherwise
428  } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429  FoundOuter.isAmbiguous()) {
430  // - if the name is found in the context of the entire
431  // postfix-expression and does not name a class template, the name
432  // found in the class of the object expression is used, otherwise
433  FoundOuter.clear();
434  } else if (!Found.isSuppressingDiagnostics()) {
435  // - if the name found is a class template, it must refer to the same
436  // entity as the one found in the class of the object expression,
437  // otherwise the program is ill-formed.
438  if (!Found.isSingleResult() ||
439  Found.getFoundDecl()->getCanonicalDecl()
440  != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
441  Diag(Found.getNameLoc(),
442  diag::ext_nested_name_member_ref_lookup_ambiguous)
443  << Found.getLookupName()
444  << ObjectType;
446  diag::note_ambig_member_ref_object_type)
447  << ObjectType;
448  Diag(FoundOuter.getFoundDecl()->getLocation(),
449  diag::note_ambig_member_ref_scope);
450 
451  // Recover by taking the template that we found in the object
452  // expression's type.
453  }
454  }
455  }
456 }
457 
459  SourceLocation Less,
460  SourceLocation Greater) {
461  if (TemplateName.isInvalid())
462  return;
463 
464  DeclarationNameInfo NameInfo;
465  CXXScopeSpec SS;
466  LookupNameKind LookupKind;
467 
468  DeclContext *LookupCtx = nullptr;
469  NamedDecl *Found = nullptr;
470 
471  // Figure out what name we looked up.
472  if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473  NameInfo = ME->getMemberNameInfo();
474  SS.Adopt(ME->getQualifierLoc());
475  LookupKind = LookupMemberName;
476  LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477  Found = ME->getMemberDecl();
478  } else {
479  auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480  NameInfo = DRE->getNameInfo();
481  SS.Adopt(DRE->getQualifierLoc());
482  LookupKind = LookupOrdinaryName;
483  Found = DRE->getFoundDecl();
484  }
485 
486  // Try to correct the name by looking for templates and C++ named casts.
487  struct TemplateCandidateFilter : CorrectionCandidateCallback {
488  TemplateCandidateFilter() {
489  WantTypeSpecifiers = false;
490  WantExpressionKeywords = false;
491  WantRemainingKeywords = false;
492  WantCXXNamedCasts = true;
493  };
494  bool ValidateCandidate(const TypoCorrection &Candidate) override {
495  if (auto *ND = Candidate.getCorrectionDecl())
496  return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497  return Candidate.isKeyword();
498  }
499  };
500 
501  DeclarationName Name = NameInfo.getName();
502  if (TypoCorrection Corrected =
503  CorrectTypo(NameInfo, LookupKind, S, &SS,
504  llvm::make_unique<TemplateCandidateFilter>(),
505  CTK_ErrorRecovery, LookupCtx)) {
506  auto *ND = Corrected.getFoundDecl();
507  if (ND)
508  ND = isAcceptableTemplateName(Context, ND,
509  /*AllowFunctionTemplates*/ true);
510  if (ND || Corrected.isKeyword()) {
511  if (LookupCtx) {
512  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514  Name.getAsString() == CorrectedStr;
515  diagnoseTypo(Corrected,
516  PDiag(diag::err_non_template_in_member_template_id_suggest)
517  << Name << LookupCtx << DroppedSpecifier
518  << SS.getRange(), false);
519  } else {
520  diagnoseTypo(Corrected,
521  PDiag(diag::err_non_template_in_template_id_suggest)
522  << Name, false);
523  }
524  if (Found)
525  Diag(Found->getLocation(),
526  diag::note_non_template_in_template_id_found);
527  return;
528  }
529  }
530 
531  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532  << Name << SourceRange(Less, Greater);
533  if (Found)
534  Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
535 }
536 
537 /// ActOnDependentIdExpression - Handle a dependent id-expression that
538 /// was just parsed. This is only possible with an explicit scope
539 /// specifier naming a dependent type.
542  SourceLocation TemplateKWLoc,
543  const DeclarationNameInfo &NameInfo,
544  bool isAddressOfOperand,
545  const TemplateArgumentListInfo *TemplateArgs) {
546  DeclContext *DC = getFunctionLevelDeclContext();
547 
548  // C++11 [expr.prim.general]p12:
549  // An id-expression that denotes a non-static data member or non-static
550  // member function of a class can only be used:
551  // (...)
552  // - if that id-expression denotes a non-static data member and it
553  // appears in an unevaluated operand.
554  //
555  // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556  // CXXDependentScopeMemberExpr. The former can instantiate to either
557  // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558  // always a MemberExpr.
559  bool MightBeCxx11UnevalField =
560  getLangOpts().CPlusPlus11 && isUnevaluatedContext();
561 
562  // Check if the nested name specifier is an enum type.
563  bool IsEnum = false;
564  if (NestedNameSpecifier *NNS = SS.getScopeRep())
565  IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
566 
567  if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
568  isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
569  QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
570 
571  // Since the 'this' expression is synthesized, we don't need to
572  // perform the double-lookup check.
573  NamedDecl *FirstQualifierInScope = nullptr;
574 
576  Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577  /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578  FirstQualifierInScope, NameInfo, TemplateArgs);
579  }
580 
581  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
582 }
583 
586  SourceLocation TemplateKWLoc,
587  const DeclarationNameInfo &NameInfo,
588  const TemplateArgumentListInfo *TemplateArgs) {
590  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
591  TemplateArgs);
592 }
593 
594 
595 /// Determine whether we would be unable to instantiate this template (because
596 /// it either has no definition, or is in the process of being instantiated).
598  NamedDecl *Instantiation,
599  bool InstantiatedFromMember,
600  const NamedDecl *Pattern,
601  const NamedDecl *PatternDef,
603  bool Complain /*= true*/) {
604  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605  isa<VarDecl>(Instantiation));
606 
607  bool IsEntityBeingDefined = false;
608  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609  IsEntityBeingDefined = TD->isBeingDefined();
610 
611  if (PatternDef && !IsEntityBeingDefined) {
612  NamedDecl *SuggestedDef = nullptr;
613  if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614  /*OnlyNeedComplete*/false)) {
615  // If we're allowed to diagnose this and recover, do so.
616  bool Recover = Complain && !isSFINAEContext();
617  if (Complain)
618  diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
620  return !Recover;
621  }
622  return false;
623  }
624 
625  if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
626  return true;
627 
629  QualType InstantiationTy;
630  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631  InstantiationTy = Context.getTypeDeclType(TD);
632  if (PatternDef) {
633  Diag(PointOfInstantiation,
634  diag::err_template_instantiate_within_definition)
635  << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
636  << InstantiationTy;
637  // Not much point in noting the template declaration here, since
638  // we're lexically inside it.
639  Instantiation->setInvalidDecl();
640  } else if (InstantiatedFromMember) {
641  if (isa<FunctionDecl>(Instantiation)) {
642  Diag(PointOfInstantiation,
643  diag::err_explicit_instantiation_undefined_member)
644  << /*member function*/ 1 << Instantiation->getDeclName()
645  << Instantiation->getDeclContext();
646  Note = diag::note_explicit_instantiation_here;
647  } else {
648  assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
649  Diag(PointOfInstantiation,
650  diag::err_implicit_instantiate_member_undefined)
651  << InstantiationTy;
652  Note = diag::note_member_declared_at;
653  }
654  } else {
655  if (isa<FunctionDecl>(Instantiation)) {
656  Diag(PointOfInstantiation,
657  diag::err_explicit_instantiation_undefined_func_template)
658  << Pattern;
659  Note = diag::note_explicit_instantiation_here;
660  } else if (isa<TagDecl>(Instantiation)) {
661  Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662  << (TSK != TSK_ImplicitInstantiation)
663  << InstantiationTy;
664  Note = diag::note_template_decl_here;
665  } else {
666  assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667  if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668  Diag(PointOfInstantiation,
669  diag::err_explicit_instantiation_undefined_var_template)
670  << Instantiation;
671  Instantiation->setInvalidDecl();
672  } else
673  Diag(PointOfInstantiation,
674  diag::err_explicit_instantiation_undefined_member)
675  << /*static data member*/ 2 << Instantiation->getDeclName()
676  << Instantiation->getDeclContext();
677  Note = diag::note_explicit_instantiation_here;
678  }
679  }
680  if (Note) // Diagnostics were emitted.
681  Diag(Pattern->getLocation(), Note.getValue());
682 
683  // In general, Instantiation isn't marked invalid to get more than one
684  // error for multiple undefined instantiations. But the code that does
685  // explicit declaration -> explicit definition conversion can't handle
686  // invalid declarations, so mark as invalid in that case.
688  Instantiation->setInvalidDecl();
689  return true;
690 }
691 
692 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693 /// that the template parameter 'PrevDecl' is being shadowed by a new
694 /// declaration at location Loc. Returns true to indicate that this is
695 /// an error, and false otherwise.
697  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
698 
699  // Microsoft Visual C++ permits template parameters to be shadowed.
700  if (getLangOpts().MicrosoftExt)
701  return;
702 
703  // C++ [temp.local]p4:
704  // A template-parameter shall not be redeclared within its
705  // scope (including nested scopes).
706  Diag(Loc, diag::err_template_param_shadow)
707  << cast<NamedDecl>(PrevDecl)->getDeclName();
708  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
709 }
710 
711 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
712 /// the parameter D to reference the templated declaration and return a pointer
713 /// to the template declaration. Otherwise, do nothing to D and return null.
715  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716  D = Temp->getTemplatedDecl();
717  return Temp;
718  }
719  return nullptr;
720 }
721 
723  SourceLocation EllipsisLoc) const {
724  assert(Kind == Template &&
725  "Only template template arguments can be pack expansions here");
726  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727  "Template template argument pack expansion without packs");
728  ParsedTemplateArgument Result(*this);
729  Result.EllipsisLoc = EllipsisLoc;
730  return Result;
731 }
732 
734  const ParsedTemplateArgument &Arg) {
735 
736  switch (Arg.getKind()) {
738  TypeSourceInfo *DI;
739  QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
740  if (!DI)
741  DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
742  return TemplateArgumentLoc(TemplateArgument(T), DI);
743  }
744 
746  Expr *E = static_cast<Expr *>(Arg.getAsExpr());
748  }
749 
751  TemplateName Template = Arg.getAsTemplate().get();
752  TemplateArgument TArg;
753  if (Arg.getEllipsisLoc().isValid())
754  TArg = TemplateArgument(Template, Optional<unsigned int>());
755  else
756  TArg = Template;
757  return TemplateArgumentLoc(TArg,
759  SemaRef.Context),
760  Arg.getLocation(),
761  Arg.getEllipsisLoc());
762  }
763  }
764 
765  llvm_unreachable("Unhandled parsed template argument");
766 }
767 
768 /// \brief Translates template arguments as provided by the parser
769 /// into template arguments used by semantic analysis.
771  TemplateArgumentListInfo &TemplateArgs) {
772  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
773  TemplateArgs.addArgument(translateTemplateArgument(*this,
774  TemplateArgsIn[I]));
775 }
776 
778  SourceLocation Loc,
779  IdentifierInfo *Name) {
780  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
782  if (PrevDecl && PrevDecl->isTemplateParameter())
783  SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784 }
785 
786 /// ActOnTypeParameter - Called when a C++ template type parameter
787 /// (e.g., "typename T") has been parsed. Typename specifies whether
788 /// the keyword "typename" was used to declare the type parameter
789 /// (otherwise, "class" was used), and KeyLoc is the location of the
790 /// "class" or "typename" keyword. ParamName is the name of the
791 /// parameter (NULL indicates an unnamed template parameter) and
792 /// ParamNameLoc is the location of the parameter name (if any).
793 /// If the type parameter has a default argument, it will be added
794 /// later via ActOnTypeParameterDefault.
796  SourceLocation EllipsisLoc,
797  SourceLocation KeyLoc,
798  IdentifierInfo *ParamName,
799  SourceLocation ParamNameLoc,
800  unsigned Depth, unsigned Position,
801  SourceLocation EqualLoc,
802  ParsedType DefaultArg) {
803  assert(S->isTemplateParamScope() &&
804  "Template type parameter not in template parameter scope!");
805 
806  SourceLocation Loc = ParamNameLoc;
807  if (!ParamName)
808  Loc = KeyLoc;
809 
810  bool IsParameterPack = EllipsisLoc.isValid();
811  TemplateTypeParmDecl *Param
813  KeyLoc, Loc, Depth, Position, ParamName,
814  Typename, IsParameterPack);
815  Param->setAccess(AS_public);
816 
817  if (ParamName) {
818  maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
819 
820  // Add the template parameter into the current scope.
821  S->AddDecl(Param);
822  IdResolver.AddDecl(Param);
823  }
824 
825  // C++0x [temp.param]p9:
826  // A default template-argument may be specified for any kind of
827  // template-parameter that is not a template parameter pack.
828  if (DefaultArg && IsParameterPack) {
829  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
830  DefaultArg = nullptr;
831  }
832 
833  // Handle the default argument, if provided.
834  if (DefaultArg) {
835  TypeSourceInfo *DefaultTInfo;
836  GetTypeFromParser(DefaultArg, &DefaultTInfo);
837 
838  assert(DefaultTInfo && "expected source information for type");
839 
840  // Check for unexpanded parameter packs.
841  if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
842  UPPC_DefaultArgument))
843  return Param;
844 
845  // Check the template argument itself.
846  if (CheckTemplateArgument(Param, DefaultTInfo)) {
847  Param->setInvalidDecl();
848  return Param;
849  }
850 
851  Param->setDefaultArgument(DefaultTInfo);
852  }
853 
854  return Param;
855 }
856 
857 /// \brief Check that the type of a non-type template parameter is
858 /// well-formed.
859 ///
860 /// \returns the (possibly-promoted) parameter type if valid;
861 /// otherwise, produces a diagnostic and returns a NULL type.
863  SourceLocation Loc) {
864  if (TSI->getType()->isUndeducedType()) {
865  // C++1z [temp.dep.expr]p3:
866  // An id-expression is type-dependent if it contains
867  // - an identifier associated by name lookup with a non-type
868  // template-parameter declared with a type that contains a
869  // placeholder type (7.1.7.4),
870  TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
871  }
872 
873  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
874 }
875 
877  SourceLocation Loc) {
878  // We don't allow variably-modified types as the type of non-type template
879  // parameters.
880  if (T->isVariablyModifiedType()) {
881  Diag(Loc, diag::err_variably_modified_nontype_template_param)
882  << T;
883  return QualType();
884  }
885 
886  // C++ [temp.param]p4:
887  //
888  // A non-type template-parameter shall have one of the following
889  // (optionally cv-qualified) types:
890  //
891  // -- integral or enumeration type,
892  if (T->isIntegralOrEnumerationType() ||
893  // -- pointer to object or pointer to function,
894  T->isPointerType() ||
895  // -- reference to object or reference to function,
896  T->isReferenceType() ||
897  // -- pointer to member,
898  T->isMemberPointerType() ||
899  // -- std::nullptr_t.
900  T->isNullPtrType() ||
901  // If T is a dependent type, we can't do the check now, so we
902  // assume that it is well-formed.
903  T->isDependentType() ||
904  // Allow use of auto in template parameter declarations.
905  T->isUndeducedType()) {
906  // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907  // are ignored when determining its type.
908  return T.getUnqualifiedType();
909  }
910 
911  // C++ [temp.param]p8:
912  //
913  // A non-type template-parameter of type "array of T" or
914  // "function returning T" is adjusted to be of type "pointer to
915  // T" or "pointer to function returning T", respectively.
916  else if (T->isArrayType() || T->isFunctionType())
917  return Context.getDecayedType(T);
918 
919  Diag(Loc, diag::err_template_nontype_parm_bad_type)
920  << T;
921 
922  return QualType();
923 }
924 
926  unsigned Depth,
927  unsigned Position,
928  SourceLocation EqualLoc,
929  Expr *Default) {
930  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
931 
932  // Check that we have valid decl-specifiers specified.
933  auto CheckValidDeclSpecifiers = [this, &D] {
934  // C++ [temp.param]
935  // p1
936  // template-parameter:
937  // ...
938  // parameter-declaration
939  // p2
940  // ... A storage class shall not be specified in a template-parameter
941  // declaration.
942  // [dcl.typedef]p1:
943  // The typedef specifier [...] shall not be used in the decl-specifier-seq
944  // of a parameter-declaration
945  const DeclSpec &DS = D.getDeclSpec();
946  auto EmitDiag = [this](SourceLocation Loc) {
947  Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
948  << FixItHint::CreateRemoval(Loc);
949  };
951  EmitDiag(DS.getStorageClassSpecLoc());
952 
954  EmitDiag(DS.getThreadStorageClassSpecLoc());
955 
956  // [dcl.inline]p1:
957  // The inline specifier can be applied only to the declaration or
958  // definition of a variable or function.
959 
960  if (DS.isInlineSpecified())
961  EmitDiag(DS.getInlineSpecLoc());
962 
963  // [dcl.constexpr]p1:
964  // The constexpr specifier shall be applied only to the definition of a
965  // variable or variable template or the declaration of a function or
966  // function template.
967 
968  if (DS.isConstexprSpecified())
969  EmitDiag(DS.getConstexprSpecLoc());
970 
971  // [dcl.fct.spec]p1:
972  // Function-specifiers can be used only in function declarations.
973 
974  if (DS.isVirtualSpecified())
975  EmitDiag(DS.getVirtualSpecLoc());
976 
977  if (DS.isExplicitSpecified())
978  EmitDiag(DS.getExplicitSpecLoc());
979 
980  if (DS.isNoreturnSpecified())
981  EmitDiag(DS.getNoreturnSpecLoc());
982  };
983 
984  CheckValidDeclSpecifiers();
985 
986  if (TInfo->getType()->isUndeducedType()) {
988  diag::warn_cxx14_compat_template_nontype_parm_auto_type)
989  << QualType(TInfo->getType()->getContainedAutoType(), 0);
990  }
991 
992  assert(S->isTemplateParamScope() &&
993  "Non-type template parameter not in template parameter scope!");
994  bool Invalid = false;
995 
996  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
997  if (T.isNull()) {
998  T = Context.IntTy; // Recover with an 'int' type.
999  Invalid = true;
1000  }
1001 
1002  IdentifierInfo *ParamName = D.getIdentifier();
1003  bool IsParameterPack = D.hasEllipsis();
1006  D.getLocStart(),
1007  D.getIdentifierLoc(),
1008  Depth, Position, ParamName, T,
1009  IsParameterPack, TInfo);
1010  Param->setAccess(AS_public);
1011 
1012  if (Invalid)
1013  Param->setInvalidDecl();
1014 
1015  if (ParamName) {
1017  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 (Default && IsParameterPack) {
1028  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1029  Default = nullptr;
1030  }
1031 
1032  // Check the well-formedness of the default template argument, if provided.
1033  if (Default) {
1034  // Check for unexpanded parameter packs.
1035  if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1036  return Param;
1037 
1038  TemplateArgument Converted;
1039  ExprResult DefaultRes =
1040  CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1041  if (DefaultRes.isInvalid()) {
1042  Param->setInvalidDecl();
1043  return Param;
1044  }
1045  Default = DefaultRes.get();
1046 
1047  Param->setDefaultArgument(Default);
1048  }
1049 
1050  return Param;
1051 }
1052 
1053 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1054 /// parameter (e.g. T in template <template <typename> class T> class array)
1055 /// has been parsed. S is the current scope.
1057  SourceLocation TmpLoc,
1058  TemplateParameterList *Params,
1059  SourceLocation EllipsisLoc,
1060  IdentifierInfo *Name,
1061  SourceLocation NameLoc,
1062  unsigned Depth,
1063  unsigned Position,
1064  SourceLocation EqualLoc,
1065  ParsedTemplateArgument Default) {
1066  assert(S->isTemplateParamScope() &&
1067  "Template template parameter not in template parameter scope!");
1068 
1069  // Construct the parameter object.
1070  bool IsParameterPack = EllipsisLoc.isValid();
1071  TemplateTemplateParmDecl *Param =
1073  NameLoc.isInvalid()? TmpLoc : NameLoc,
1074  Depth, Position, IsParameterPack,
1075  Name, Params);
1076  Param->setAccess(AS_public);
1077 
1078  // If the template template parameter has a name, then link the identifier
1079  // into the scope and lookup mechanisms.
1080  if (Name) {
1081  maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1082 
1083  S->AddDecl(Param);
1084  IdResolver.AddDecl(Param);
1085  }
1086 
1087  if (Params->size() == 0) {
1088  Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1089  << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1090  Param->setInvalidDecl();
1091  }
1092 
1093  // C++0x [temp.param]p9:
1094  // A default template-argument may be specified for any kind of
1095  // template-parameter that is not a template parameter pack.
1096  if (IsParameterPack && !Default.isInvalid()) {
1097  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1098  Default = ParsedTemplateArgument();
1099  }
1100 
1101  if (!Default.isInvalid()) {
1102  // Check only that we have a template template argument. We don't want to
1103  // try to check well-formedness now, because our template template parameter
1104  // might have dependent types in its template parameters, which we wouldn't
1105  // be able to match now.
1106  //
1107  // If none of the template template parameter's template arguments mention
1108  // other template parameters, we could actually perform more checking here.
1109  // However, it isn't worth doing.
1110  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1111  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1112  Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1113  << DefaultArg.getSourceRange();
1114  return Param;
1115  }
1116 
1117  // Check for unexpanded parameter packs.
1118  if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1119  DefaultArg.getArgument().getAsTemplate(),
1120  UPPC_DefaultArgument))
1121  return Param;
1122 
1123  Param->setDefaultArgument(Context, DefaultArg);
1124  }
1125 
1126  return Param;
1127 }
1128 
1129 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1130 /// constrained by RequiresClause, that contains the template parameters in
1131 /// Params.
1134  SourceLocation ExportLoc,
1135  SourceLocation TemplateLoc,
1136  SourceLocation LAngleLoc,
1137  ArrayRef<NamedDecl *> Params,
1138  SourceLocation RAngleLoc,
1139  Expr *RequiresClause) {
1140  if (ExportLoc.isValid())
1141  Diag(ExportLoc, diag::warn_template_export_unsupported);
1142 
1144  Context, TemplateLoc, LAngleLoc,
1145  llvm::makeArrayRef(Params.data(), Params.size()),
1146  RAngleLoc, RequiresClause);
1147 }
1148 
1149 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1150  if (SS.isSet())
1152 }
1153 
1154 DeclResult
1155 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1156  SourceLocation KWLoc, CXXScopeSpec &SS,
1157  IdentifierInfo *Name, SourceLocation NameLoc,
1159  TemplateParameterList *TemplateParams,
1160  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1161  SourceLocation FriendLoc,
1162  unsigned NumOuterTemplateParamLists,
1163  TemplateParameterList** OuterTemplateParamLists,
1164  SkipBodyInfo *SkipBody) {
1165  assert(TemplateParams && TemplateParams->size() > 0 &&
1166  "No template parameters");
1167  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1168  bool Invalid = false;
1169 
1170  // Check that we can declare a template here.
1171  if (CheckTemplateDeclScope(S, TemplateParams))
1172  return true;
1173 
1175  assert(Kind != TTK_Enum && "can't build template of enumerated type");
1176 
1177  // There is no such thing as an unnamed class template.
1178  if (!Name) {
1179  Diag(KWLoc, diag::err_template_unnamed_class);
1180  return true;
1181  }
1182 
1183  // Find any previous declaration with this name. For a friend with no
1184  // scope explicitly specified, we only look for tag declarations (per
1185  // C++11 [basic.lookup.elab]p2).
1186  DeclContext *SemanticContext;
1187  LookupResult Previous(*this, Name, NameLoc,
1188  (SS.isEmpty() && TUK == TUK_Friend)
1189  ? LookupTagName : LookupOrdinaryName,
1190  forRedeclarationInCurContext());
1191  if (SS.isNotEmpty() && !SS.isInvalid()) {
1192  SemanticContext = computeDeclContext(SS, true);
1193  if (!SemanticContext) {
1194  // FIXME: Horrible, horrible hack! We can't currently represent this
1195  // in the AST, and historically we have just ignored such friend
1196  // class templates, so don't complain here.
1197  Diag(NameLoc, TUK == TUK_Friend
1198  ? diag::warn_template_qualified_friend_ignored
1199  : diag::err_template_qualified_declarator_no_match)
1200  << SS.getScopeRep() << SS.getRange();
1201  return TUK != TUK_Friend;
1202  }
1203 
1204  if (RequireCompleteDeclContext(SS, SemanticContext))
1205  return true;
1206 
1207  // If we're adding a template to a dependent context, we may need to
1208  // rebuilding some of the types used within the template parameter list,
1209  // now that we know what the current instantiation is.
1210  if (SemanticContext->isDependentContext()) {
1211  ContextRAII SavedContext(*this, SemanticContext);
1212  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1213  Invalid = true;
1214  } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1215  diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1216 
1217  LookupQualifiedName(Previous, SemanticContext);
1218  } else {
1219  SemanticContext = CurContext;
1220 
1221  // C++14 [class.mem]p14:
1222  // If T is the name of a class, then each of the following shall have a
1223  // name different from T:
1224  // -- every member template of class T
1225  if (TUK != TUK_Friend &&
1226  DiagnoseClassNameShadow(SemanticContext,
1227  DeclarationNameInfo(Name, NameLoc)))
1228  return true;
1229 
1230  LookupName(Previous, S);
1231  }
1232 
1233  if (Previous.isAmbiguous())
1234  return true;
1235 
1236  NamedDecl *PrevDecl = nullptr;
1237  if (Previous.begin() != Previous.end())
1238  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1239 
1240  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1241  // Maybe we will complain about the shadowed template parameter.
1242  DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1243  // Just pretend that we didn't see the previous declaration.
1244  PrevDecl = nullptr;
1245  }
1246 
1247  // If there is a previous declaration with the same name, check
1248  // whether this is a valid redeclaration.
1249  ClassTemplateDecl *PrevClassTemplate =
1250  dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1251 
1252  // We may have found the injected-class-name of a class template,
1253  // class template partial specialization, or class template specialization.
1254  // In these cases, grab the template that is being defined or specialized.
1255  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1256  cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1257  PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1258  PrevClassTemplate
1259  = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1260  if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1261  PrevClassTemplate
1262  = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1263  ->getSpecializedTemplate();
1264  }
1265  }
1266 
1267  if (TUK == TUK_Friend) {
1268  // C++ [namespace.memdef]p3:
1269  // [...] When looking for a prior declaration of a class or a function
1270  // declared as a friend, and when the name of the friend class or
1271  // function is neither a qualified name nor a template-id, scopes outside
1272  // the innermost enclosing namespace scope are not considered.
1273  if (!SS.isSet()) {
1274  DeclContext *OutermostContext = CurContext;
1275  while (!OutermostContext->isFileContext())
1276  OutermostContext = OutermostContext->getLookupParent();
1277 
1278  if (PrevDecl &&
1279  (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1280  OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1281  SemanticContext = PrevDecl->getDeclContext();
1282  } else {
1283  // Declarations in outer scopes don't matter. However, the outermost
1284  // context we computed is the semantic context for our new
1285  // declaration.
1286  PrevDecl = PrevClassTemplate = nullptr;
1287  SemanticContext = OutermostContext;
1288 
1289  // Check that the chosen semantic context doesn't already contain a
1290  // declaration of this name as a non-tag type.
1291  Previous.clear(LookupOrdinaryName);
1292  DeclContext *LookupContext = SemanticContext;
1293  while (LookupContext->isTransparentContext())
1294  LookupContext = LookupContext->getLookupParent();
1295  LookupQualifiedName(Previous, LookupContext);
1296 
1297  if (Previous.isAmbiguous())
1298  return true;
1299 
1300  if (Previous.begin() != Previous.end())
1301  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1302  }
1303  }
1304  } else if (PrevDecl &&
1305  !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1306  S, SS.isValid()))
1307  PrevDecl = PrevClassTemplate = nullptr;
1308 
1309  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1310  PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1311  if (SS.isEmpty() &&
1312  !(PrevClassTemplate &&
1313  PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1314  SemanticContext->getRedeclContext()))) {
1315  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1316  Diag(Shadow->getTargetDecl()->getLocation(),
1317  diag::note_using_decl_target);
1318  Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1319  // Recover by ignoring the old declaration.
1320  PrevDecl = PrevClassTemplate = nullptr;
1321  }
1322  }
1323 
1324  // TODO Memory management; associated constraints are not always stored.
1325  Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1326 
1327  if (PrevClassTemplate) {
1328  // Ensure that the template parameter lists are compatible. Skip this check
1329  // for a friend in a dependent context: the template parameter list itself
1330  // could be dependent.
1331  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1332  !TemplateParameterListsAreEqual(TemplateParams,
1333  PrevClassTemplate->getTemplateParameters(),
1334  /*Complain=*/true,
1335  TPL_TemplateMatch))
1336  return true;
1337 
1338  // Check for matching associated constraints on redeclarations.
1339  const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1340  const bool RedeclACMismatch = [&] {
1341  if (!(CurAC || PrevAC))
1342  return false; // Nothing to check; no mismatch.
1343  if (CurAC && PrevAC) {
1344  llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1345  CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1346  PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1347  if (CurACInfo == PrevACInfo)
1348  return false; // All good; no mismatch.
1349  }
1350  return true;
1351  }();
1352 
1353  if (RedeclACMismatch) {
1354  Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1355  diag::err_template_different_associated_constraints);
1356  Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1357  diag::note_template_prev_declaration) << /*declaration*/0;
1358  return true;
1359  }
1360 
1361  // C++ [temp.class]p4:
1362  // In a redeclaration, partial specialization, explicit
1363  // specialization or explicit instantiation of a class template,
1364  // the class-key shall agree in kind with the original class
1365  // template declaration (7.1.5.3).
1366  RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1367  if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1368  TUK == TUK_Definition, KWLoc, Name)) {
1369  Diag(KWLoc, diag::err_use_with_wrong_tag)
1370  << Name
1371  << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1372  Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1373  Kind = PrevRecordDecl->getTagKind();
1374  }
1375 
1376  // Check for redefinition of this class template.
1377  if (TUK == TUK_Definition) {
1378  if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1379  // If we have a prior definition that is not visible, treat this as
1380  // simply making that previous definition visible.
1381  NamedDecl *Hidden = nullptr;
1382  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1383  SkipBody->ShouldSkip = true;
1384  auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1385  assert(Tmpl && "original definition of a class template is not a "
1386  "class template?");
1387  makeMergedDefinitionVisible(Hidden);
1388  makeMergedDefinitionVisible(Tmpl);
1389  return Def;
1390  }
1391 
1392  Diag(NameLoc, diag::err_redefinition) << Name;
1393  Diag(Def->getLocation(), diag::note_previous_definition);
1394  // FIXME: Would it make sense to try to "forget" the previous
1395  // definition, as part of error recovery?
1396  return true;
1397  }
1398  }
1399  } else if (PrevDecl) {
1400  // C++ [temp]p5:
1401  // A class template shall not have the same name as any other
1402  // template, class, function, object, enumeration, enumerator,
1403  // namespace, or type in the same scope (3.3), except as specified
1404  // in (14.5.4).
1405  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1406  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1407  return true;
1408  }
1409 
1410  // Check the template parameter list of this declaration, possibly
1411  // merging in the template parameter list from the previous class
1412  // template declaration. Skip this check for a friend in a dependent
1413  // context, because the template parameter list might be dependent.
1414  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1415  CheckTemplateParameterList(
1416  TemplateParams,
1417  PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1418  : nullptr,
1419  (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1420  SemanticContext->isDependentContext())
1421  ? TPC_ClassTemplateMember
1422  : TUK == TUK_Friend ? TPC_FriendClassTemplate
1423  : TPC_ClassTemplate))
1424  Invalid = true;
1425 
1426  if (SS.isSet()) {
1427  // If the name of the template was qualified, we must be defining the
1428  // template out-of-line.
1429  if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1430  Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1431  : diag::err_member_decl_does_not_match)
1432  << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1433  Invalid = true;
1434  }
1435  }
1436 
1437  // If this is a templated friend in a dependent context we should not put it
1438  // on the redecl chain. In some cases, the templated friend can be the most
1439  // recent declaration tricking the template instantiator to make substitutions
1440  // there.
1441  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1442  bool ShouldAddRedecl
1443  = !(TUK == TUK_Friend && CurContext->isDependentContext());
1444 
1445  CXXRecordDecl *NewClass =
1446  CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1447  PrevClassTemplate && ShouldAddRedecl ?
1448  PrevClassTemplate->getTemplatedDecl() : nullptr,
1449  /*DelayTypeCreation=*/true);
1450  SetNestedNameSpecifier(NewClass, SS);
1451  if (NumOuterTemplateParamLists > 0)
1453  Context, llvm::makeArrayRef(OuterTemplateParamLists,
1454  NumOuterTemplateParamLists));
1455 
1456  // Add alignment attributes if necessary; these attributes are checked when
1457  // the ASTContext lays out the structure.
1458  if (TUK == TUK_Definition) {
1459  AddAlignmentAttributesForRecord(NewClass);
1460  AddMsStructLayoutForRecord(NewClass);
1461  }
1462 
1463  // Attach the associated constraints when the declaration will not be part of
1464  // a decl chain.
1465  Expr *const ACtoAttach =
1466  PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1467 
1468  ClassTemplateDecl *NewTemplate
1469  = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1470  DeclarationName(Name), TemplateParams,
1471  NewClass, ACtoAttach);
1472 
1473  if (ShouldAddRedecl)
1474  NewTemplate->setPreviousDecl(PrevClassTemplate);
1475 
1476  NewClass->setDescribedClassTemplate(NewTemplate);
1477 
1478  if (ModulePrivateLoc.isValid())
1479  NewTemplate->setModulePrivate();
1480 
1481  // Build the type for the class template declaration now.
1483  T = Context.getInjectedClassNameType(NewClass, T);
1484  assert(T->isDependentType() && "Class template type is not dependent?");
1485  (void)T;
1486 
1487  // If we are providing an explicit specialization of a member that is a
1488  // class template, make a note of that.
1489  if (PrevClassTemplate &&
1490  PrevClassTemplate->getInstantiatedFromMemberTemplate())
1491  PrevClassTemplate->setMemberSpecialization();
1492 
1493  // Set the access specifier.
1494  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1495  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1496 
1497  // Set the lexical context of these templates
1498  NewClass->setLexicalDeclContext(CurContext);
1499  NewTemplate->setLexicalDeclContext(CurContext);
1500 
1501  if (TUK == TUK_Definition)
1502  NewClass->startDefinition();
1503 
1504  if (Attr)
1505  ProcessDeclAttributeList(S, NewClass, Attr);
1506 
1507  if (PrevClassTemplate)
1508  mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1509 
1510  AddPushedVisibilityAttribute(NewClass);
1511 
1512  if (TUK != TUK_Friend) {
1513  // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1514  Scope *Outer = S;
1515  while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1516  Outer = Outer->getParent();
1517  PushOnScopeChains(NewTemplate, Outer);
1518  } else {
1519  if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1520  NewTemplate->setAccess(PrevClassTemplate->getAccess());
1521  NewClass->setAccess(PrevClassTemplate->getAccess());
1522  }
1523 
1524  NewTemplate->setObjectOfFriendDecl();
1525 
1526  // Friend templates are visible in fairly strange ways.
1527  if (!CurContext->isDependentContext()) {
1528  DeclContext *DC = SemanticContext->getRedeclContext();
1529  DC->makeDeclVisibleInContext(NewTemplate);
1530  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1531  PushOnScopeChains(NewTemplate, EnclosingScope,
1532  /* AddToContext = */ false);
1533  }
1534 
1535  FriendDecl *Friend = FriendDecl::Create(
1536  Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1537  Friend->setAccess(AS_public);
1538  CurContext->addDecl(Friend);
1539  }
1540 
1541  if (PrevClassTemplate)
1542  CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1543 
1544  if (Invalid) {
1545  NewTemplate->setInvalidDecl();
1546  NewClass->setInvalidDecl();
1547  }
1548 
1549  ActOnDocumentableDecl(NewTemplate);
1550 
1551  return NewTemplate;
1552 }
1553 
1554 namespace {
1555 /// Transform to convert portions of a constructor declaration into the
1556 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1557 struct ConvertConstructorToDeductionGuideTransform {
1558  ConvertConstructorToDeductionGuideTransform(Sema &S,
1559  ClassTemplateDecl *Template)
1560  : SemaRef(S), Template(Template) {}
1561 
1562  Sema &SemaRef;
1563  ClassTemplateDecl *Template;
1564 
1565  DeclContext *DC = Template->getDeclContext();
1566  CXXRecordDecl *Primary = Template->getTemplatedDecl();
1567  DeclarationName DeductionGuideName =
1569 
1570  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1571 
1572  // Index adjustment to apply to convert depth-1 template parameters into
1573  // depth-0 template parameters.
1574  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1575 
1576  /// Transform a constructor declaration into a deduction guide.
1577  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1578  CXXConstructorDecl *CD) {
1580 
1581  LocalInstantiationScope Scope(SemaRef);
1582 
1583  // C++ [over.match.class.deduct]p1:
1584  // -- For each constructor of the class template designated by the
1585  // template-name, a function template with the following properties:
1586 
1587  // -- The template parameters are the template parameters of the class
1588  // template followed by the template parameters (including default
1589  // template arguments) of the constructor, if any.
1590  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1591  if (FTD) {
1592  TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1593  SmallVector<NamedDecl *, 16> AllParams;
1594  AllParams.reserve(TemplateParams->size() + InnerParams->size());
1595  AllParams.insert(AllParams.begin(),
1596  TemplateParams->begin(), TemplateParams->end());
1597  SubstArgs.reserve(InnerParams->size());
1598 
1599  // Later template parameters could refer to earlier ones, so build up
1600  // a list of substituted template arguments as we go.
1601  for (NamedDecl *Param : *InnerParams) {
1603  Args.addOuterTemplateArguments(SubstArgs);
1604  Args.addOuterRetainedLevel();
1605  NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1606  if (!NewParam)
1607  return nullptr;
1608  AllParams.push_back(NewParam);
1609  SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1610  SemaRef.Context.getInjectedTemplateArg(NewParam)));
1611  }
1612  TemplateParams = TemplateParameterList::Create(
1613  SemaRef.Context, InnerParams->getTemplateLoc(),
1614  InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1615  /*FIXME: RequiresClause*/ nullptr);
1616  }
1617 
1618  // If we built a new template-parameter-list, track that we need to
1619  // substitute references to the old parameters into references to the
1620  // new ones.
1622  if (FTD) {
1623  Args.addOuterTemplateArguments(SubstArgs);
1624  Args.addOuterRetainedLevel();
1625  }
1626 
1629  assert(FPTL && "no prototype for constructor declaration");
1630 
1631  // Transform the type of the function, adjusting the return type and
1632  // replacing references to the old parameters with references to the
1633  // new ones.
1634  TypeLocBuilder TLB;
1636  QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1637  if (NewType.isNull())
1638  return nullptr;
1639  TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1640 
1641  return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1642  CD->getLocStart(), CD->getLocation(),
1643  CD->getLocEnd());
1644  }
1645 
1646  /// Build a deduction guide with the specified parameter types.
1647  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1648  SourceLocation Loc = Template->getLocation();
1649 
1650  // Build the requested type.
1652  EPI.HasTrailingReturn = true;
1653  QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1654  DeductionGuideName, EPI);
1655  TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1656 
1657  FunctionProtoTypeLoc FPTL =
1659 
1660  // Build the parameters, needed during deduction / substitution.
1662  for (auto T : ParamTypes) {
1663  ParmVarDecl *NewParam = ParmVarDecl::Create(
1664  SemaRef.Context, DC, Loc, Loc, nullptr, T,
1665  SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1666  NewParam->setScopeInfo(0, Params.size());
1667  FPTL.setParam(Params.size(), NewParam);
1668  Params.push_back(NewParam);
1669  }
1670 
1671  return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1672  Loc, Loc, Loc);
1673  }
1674 
1675 private:
1676  /// Transform a constructor template parameter into a deduction guide template
1677  /// parameter, rebuilding any internal references to earlier parameters and
1678  /// renumbering as we go.
1679  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1681  if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1682  // TemplateTypeParmDecl's index cannot be changed after creation, so
1683  // substitute it directly.
1684  auto *NewTTP = TemplateTypeParmDecl::Create(
1685  SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1686  /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1687  TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1688  TTP->isParameterPack());
1689  if (TTP->hasDefaultArgument()) {
1690  TypeSourceInfo *InstantiatedDefaultArg =
1691  SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1692  TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1693  if (InstantiatedDefaultArg)
1694  NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1695  }
1696  SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1697  NewTTP);
1698  return NewTTP;
1699  }
1700 
1701  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1702  return transformTemplateParameterImpl(TTP, Args);
1703 
1704  return transformTemplateParameterImpl(
1705  cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1706  }
1707  template<typename TemplateParmDecl>
1708  TemplateParmDecl *
1709  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1711  // Ask the template instantiator to do the heavy lifting for us, then adjust
1712  // the index of the parameter once it's done.
1713  auto *NewParam =
1714  cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1715  assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1716  NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1717  return NewParam;
1718  }
1719 
1720  QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1724  SmallVector<QualType, 4> ParamTypes;
1725  const FunctionProtoType *T = TL.getTypePtr();
1726 
1727  // -- The types of the function parameters are those of the constructor.
1728  for (auto *OldParam : TL.getParams()) {
1729  ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1730  if (!NewParam)
1731  return QualType();
1732  ParamTypes.push_back(NewParam->getType());
1733  Params.push_back(NewParam);
1734  }
1735 
1736  // -- The return type is the class template specialization designated by
1737  // the template-name and template arguments corresponding to the
1738  // template parameters obtained from the class template.
1739  //
1740  // We use the injected-class-name type of the primary template instead.
1741  // This has the convenient property that it is different from any type that
1742  // the user can write in a deduction-guide (because they cannot enter the
1743  // context of the template), so implicit deduction guides can never collide
1744  // with explicit ones.
1745  QualType ReturnType = DeducedType;
1746  TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1747 
1748  // Resolving a wording defect, we also inherit the variadicness of the
1749  // constructor.
1751  EPI.Variadic = T->isVariadic();
1752  EPI.HasTrailingReturn = true;
1753 
1754  QualType Result = SemaRef.BuildFunctionType(
1755  ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1756  if (Result.isNull())
1757  return QualType();
1758 
1759  FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1761  NewTL.setLParenLoc(TL.getLParenLoc());
1762  NewTL.setRParenLoc(TL.getRParenLoc());
1764  NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1765  for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1766  NewTL.setParam(I, Params[I]);
1767 
1768  return Result;
1769  }
1770 
1771  ParmVarDecl *
1772  transformFunctionTypeParam(ParmVarDecl *OldParam,
1774  TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1775  TypeSourceInfo *NewDI;
1776  if (!Args.getNumLevels())
1777  NewDI = OldDI;
1778  else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1779  // Expand out the one and only element in each inner pack.
1780  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1781  NewDI =
1782  SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1783  OldParam->getLocation(), OldParam->getDeclName());
1784  if (!NewDI) return nullptr;
1785  NewDI =
1786  SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1787  PackTL.getTypePtr()->getNumExpansions());
1788  } else
1789  NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1790  OldParam->getDeclName());
1791  if (!NewDI)
1792  return nullptr;
1793 
1794  // Canonicalize the type. This (for instance) replaces references to
1795  // typedef members of the current instantiations with the definitions of
1796  // those typedefs, avoiding triggering instantiation of the deduced type
1797  // during deduction.
1798  // FIXME: It would be preferable to retain type sugar and source
1799  // information here (and handle this in substitution instead).
1800  NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1801  SemaRef.Context.getCanonicalType(NewDI->getType()),
1802  OldParam->getLocation());
1803 
1804  // Resolving a wording defect, we also inherit default arguments from the
1805  // constructor.
1806  ExprResult NewDefArg;
1807  if (OldParam->hasDefaultArg()) {
1808  NewDefArg = Args.getNumLevels()
1809  ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1810  : OldParam->getDefaultArg();
1811  if (NewDefArg.isInvalid())
1812  return nullptr;
1813  }
1814 
1815  ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1816  OldParam->getInnerLocStart(),
1817  OldParam->getLocation(),
1818  OldParam->getIdentifier(),
1819  NewDI->getType(),
1820  NewDI,
1821  OldParam->getStorageClass(),
1822  NewDefArg.get());
1823  NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1824  OldParam->getFunctionScopeIndex());
1825  return NewParam;
1826  }
1827 
1828  NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1829  bool Explicit, TypeSourceInfo *TInfo,
1830  SourceLocation LocStart, SourceLocation Loc,
1831  SourceLocation LocEnd) {
1832  DeclarationNameInfo Name(DeductionGuideName, Loc);
1833  ArrayRef<ParmVarDecl *> Params =
1834  TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1835 
1836  // Build the implicit deduction guide template.
1837  auto *Guide =
1838  CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1839  Name, TInfo->getType(), TInfo, LocEnd);
1840  Guide->setImplicit();
1841  Guide->setParams(Params);
1842 
1843  for (auto *Param : Params)
1844  Param->setDeclContext(Guide);
1845 
1846  auto *GuideTemplate = FunctionTemplateDecl::Create(
1847  SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1848  GuideTemplate->setImplicit();
1849  Guide->setDescribedFunctionTemplate(GuideTemplate);
1850 
1851  if (isa<CXXRecordDecl>(DC)) {
1852  Guide->setAccess(AS_public);
1853  GuideTemplate->setAccess(AS_public);
1854  }
1855 
1856  DC->addDecl(GuideTemplate);
1857  return GuideTemplate;
1858  }
1859 };
1860 }
1861 
1863  SourceLocation Loc) {
1864  DeclContext *DC = Template->getDeclContext();
1865  if (DC->isDependentContext())
1866  return;
1867 
1868  ConvertConstructorToDeductionGuideTransform Transform(
1869  *this, cast<ClassTemplateDecl>(Template));
1870  if (!isCompleteType(Loc, Transform.DeducedType))
1871  return;
1872 
1873  // Check whether we've already declared deduction guides for this template.
1874  // FIXME: Consider storing a flag on the template to indicate this.
1875  auto Existing = DC->lookup(Transform.DeductionGuideName);
1876  for (auto *D : Existing)
1877  if (D->isImplicit())
1878  return;
1879 
1880  // In case we were expanding a pack when we attempted to declare deduction
1881  // guides, turn off pack expansion for everything we're about to do.
1882  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1883  // Create a template instantiation record to track the "instantiation" of
1884  // constructors into deduction guides.
1885  // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1886  // this substitution process actually fail?
1887  InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1888 
1889  // Convert declared constructors into deduction guide templates.
1890  // FIXME: Skip constructors for which deduction must necessarily fail (those
1891  // for which some class template parameter without a default argument never
1892  // appears in a deduced context).
1893  bool AddedAny = false;
1894  for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1895  D = D->getUnderlyingDecl();
1896  if (D->isInvalidDecl() || D->isImplicit())
1897  continue;
1898  D = cast<NamedDecl>(D->getCanonicalDecl());
1899 
1900  auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1901  auto *CD =
1902  dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1903  // Class-scope explicit specializations (MS extension) do not result in
1904  // deduction guides.
1905  if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1906  continue;
1907 
1908  Transform.transformConstructor(FTD, CD);
1909  AddedAny = true;
1910  }
1911 
1912  // C++17 [over.match.class.deduct]
1913  // -- If C is not defined or does not declare any constructors, an
1914  // additional function template derived as above from a hypothetical
1915  // constructor C().
1916  if (!AddedAny)
1917  Transform.buildSimpleDeductionGuide(None);
1918 
1919  // -- An additional function template derived as above from a hypothetical
1920  // constructor C(C), called the copy deduction candidate.
1921  cast<CXXDeductionGuideDecl>(
1922  cast<FunctionTemplateDecl>(
1923  Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1924  ->getTemplatedDecl())
1925  ->setIsCopyDeductionCandidate();
1926 }
1927 
1928 /// \brief Diagnose the presence of a default template argument on a
1929 /// template parameter, which is ill-formed in certain contexts.
1930 ///
1931 /// \returns true if the default template argument should be dropped.
1934  SourceLocation ParamLoc,
1935  SourceRange DefArgRange) {
1936  switch (TPC) {
1938  case Sema::TPC_VarTemplate:
1940  return false;
1941 
1944  // C++ [temp.param]p9:
1945  // A default template-argument shall not be specified in a
1946  // function template declaration or a function template
1947  // definition [...]
1948  // If a friend function template declaration specifies a default
1949  // template-argument, that declaration shall be a definition and shall be
1950  // the only declaration of the function template in the translation unit.
1951  // (C++98/03 doesn't have this wording; see DR226).
1952  S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1953  diag::warn_cxx98_compat_template_parameter_default_in_function_template
1954  : diag::ext_template_parameter_default_in_function_template)
1955  << DefArgRange;
1956  return false;
1957 
1959  // C++0x [temp.param]p9:
1960  // A default template-argument shall not be specified in the
1961  // template-parameter-lists of the definition of a member of a
1962  // class template that appears outside of the member's class.
1963  S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1964  << DefArgRange;
1965  return true;
1966 
1969  // C++ [temp.param]p9:
1970  // A default template-argument shall not be specified in a
1971  // friend template declaration.
1972  S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1973  << DefArgRange;
1974  return true;
1975 
1976  // FIXME: C++0x [temp.param]p9 allows default template-arguments
1977  // for friend function templates if there is only a single
1978  // declaration (and it is a definition). Strange!
1979  }
1980 
1981  llvm_unreachable("Invalid TemplateParamListContext!");
1982 }
1983 
1984 /// \brief Check for unexpanded parameter packs within the template parameters
1985 /// of a template template parameter, recursively.
1987  TemplateTemplateParmDecl *TTP) {
1988  // A template template parameter which is a parameter pack is also a pack
1989  // expansion.
1990  if (TTP->isParameterPack())
1991  return false;
1992 
1994  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1995  NamedDecl *P = Params->getParam(I);
1996  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1997  if (!NTTP->isParameterPack() &&
1998  S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1999  NTTP->getTypeSourceInfo(),
2001  return true;
2002 
2003  continue;
2004  }
2005 
2006  if (TemplateTemplateParmDecl *InnerTTP
2007  = dyn_cast<TemplateTemplateParmDecl>(P))
2008  if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2009  return true;
2010  }
2011 
2012  return false;
2013 }
2014 
2015 /// \brief Checks the validity of a template parameter list, possibly
2016 /// considering the template parameter list from a previous
2017 /// declaration.
2018 ///
2019 /// If an "old" template parameter list is provided, it must be
2020 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2021 /// template parameter list.
2022 ///
2023 /// \param NewParams Template parameter list for a new template
2024 /// declaration. This template parameter list will be updated with any
2025 /// default arguments that are carried through from the previous
2026 /// template parameter list.
2027 ///
2028 /// \param OldParams If provided, template parameter list from a
2029 /// previous declaration of the same template. Default template
2030 /// arguments will be merged from the old template parameter list to
2031 /// the new template parameter list.
2032 ///
2033 /// \param TPC Describes the context in which we are checking the given
2034 /// template parameter list.
2035 ///
2036 /// \returns true if an error occurred, false otherwise.
2038  TemplateParameterList *OldParams,
2040  bool Invalid = false;
2041 
2042  // C++ [temp.param]p10:
2043  // The set of default template-arguments available for use with a
2044  // template declaration or definition is obtained by merging the
2045  // default arguments from the definition (if in scope) and all
2046  // declarations in scope in the same way default function
2047  // arguments are (8.3.6).
2048  bool SawDefaultArgument = false;
2049  SourceLocation PreviousDefaultArgLoc;
2050 
2051  // Dummy initialization to avoid warnings.
2052  TemplateParameterList::iterator OldParam = NewParams->end();
2053  if (OldParams)
2054  OldParam = OldParams->begin();
2055 
2056  bool RemoveDefaultArguments = false;
2057  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2058  NewParamEnd = NewParams->end();
2059  NewParam != NewParamEnd; ++NewParam) {
2060  // Variables used to diagnose redundant default arguments
2061  bool RedundantDefaultArg = false;
2062  SourceLocation OldDefaultLoc;
2063  SourceLocation NewDefaultLoc;
2064 
2065  // Variable used to diagnose missing default arguments
2066  bool MissingDefaultArg = false;
2067 
2068  // Variable used to diagnose non-final parameter packs
2069  bool SawParameterPack = false;
2070 
2071  if (TemplateTypeParmDecl *NewTypeParm
2072  = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2073  // Check the presence of a default argument here.
2074  if (NewTypeParm->hasDefaultArgument() &&
2076  NewTypeParm->getLocation(),
2077  NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2078  .getSourceRange()))
2079  NewTypeParm->removeDefaultArgument();
2080 
2081  // Merge default arguments for template type parameters.
2082  TemplateTypeParmDecl *OldTypeParm
2083  = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2084  if (NewTypeParm->isParameterPack()) {
2085  assert(!NewTypeParm->hasDefaultArgument() &&
2086  "Parameter packs can't have a default argument!");
2087  SawParameterPack = true;
2088  } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2089  NewTypeParm->hasDefaultArgument()) {
2090  OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2091  NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2092  SawDefaultArgument = true;
2093  RedundantDefaultArg = true;
2094  PreviousDefaultArgLoc = NewDefaultLoc;
2095  } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2096  // Merge the default argument from the old declaration to the
2097  // new declaration.
2098  NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2099  PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2100  } else if (NewTypeParm->hasDefaultArgument()) {
2101  SawDefaultArgument = true;
2102  PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2103  } else if (SawDefaultArgument)
2104  MissingDefaultArg = true;
2105  } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2106  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2107  // Check for unexpanded parameter packs.
2108  if (!NewNonTypeParm->isParameterPack() &&
2109  DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2110  NewNonTypeParm->getTypeSourceInfo(),
2111  UPPC_NonTypeTemplateParameterType)) {
2112  Invalid = true;
2113  continue;
2114  }
2115 
2116  // Check the presence of a default argument here.
2117  if (NewNonTypeParm->hasDefaultArgument() &&
2119  NewNonTypeParm->getLocation(),
2120  NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2121  NewNonTypeParm->removeDefaultArgument();
2122  }
2123 
2124  // Merge default arguments for non-type template parameters
2125  NonTypeTemplateParmDecl *OldNonTypeParm
2126  = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2127  if (NewNonTypeParm->isParameterPack()) {
2128  assert(!NewNonTypeParm->hasDefaultArgument() &&
2129  "Parameter packs can't have a default argument!");
2130  if (!NewNonTypeParm->isPackExpansion())
2131  SawParameterPack = true;
2132  } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2133  NewNonTypeParm->hasDefaultArgument()) {
2134  OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2135  NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2136  SawDefaultArgument = true;
2137  RedundantDefaultArg = true;
2138  PreviousDefaultArgLoc = NewDefaultLoc;
2139  } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2140  // Merge the default argument from the old declaration to the
2141  // new declaration.
2142  NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2143  PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2144  } else if (NewNonTypeParm->hasDefaultArgument()) {
2145  SawDefaultArgument = true;
2146  PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2147  } else if (SawDefaultArgument)
2148  MissingDefaultArg = true;
2149  } else {
2150  TemplateTemplateParmDecl *NewTemplateParm
2151  = cast<TemplateTemplateParmDecl>(*NewParam);
2152 
2153  // Check for unexpanded parameter packs, recursively.
2154  if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2155  Invalid = true;
2156  continue;
2157  }
2158 
2159  // Check the presence of a default argument here.
2160  if (NewTemplateParm->hasDefaultArgument() &&
2162  NewTemplateParm->getLocation(),
2163  NewTemplateParm->getDefaultArgument().getSourceRange()))
2164  NewTemplateParm->removeDefaultArgument();
2165 
2166  // Merge default arguments for template template parameters
2167  TemplateTemplateParmDecl *OldTemplateParm
2168  = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2169  if (NewTemplateParm->isParameterPack()) {
2170  assert(!NewTemplateParm->hasDefaultArgument() &&
2171  "Parameter packs can't have a default argument!");
2172  if (!NewTemplateParm->isPackExpansion())
2173  SawParameterPack = true;
2174  } else if (OldTemplateParm &&
2175  hasVisibleDefaultArgument(OldTemplateParm) &&
2176  NewTemplateParm->hasDefaultArgument()) {
2177  OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2178  NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2179  SawDefaultArgument = true;
2180  RedundantDefaultArg = true;
2181  PreviousDefaultArgLoc = NewDefaultLoc;
2182  } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2183  // Merge the default argument from the old declaration to the
2184  // new declaration.
2185  NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2186  PreviousDefaultArgLoc
2187  = OldTemplateParm->getDefaultArgument().getLocation();
2188  } else if (NewTemplateParm->hasDefaultArgument()) {
2189  SawDefaultArgument = true;
2190  PreviousDefaultArgLoc
2191  = NewTemplateParm->getDefaultArgument().getLocation();
2192  } else if (SawDefaultArgument)
2193  MissingDefaultArg = true;
2194  }
2195 
2196  // C++11 [temp.param]p11:
2197  // If a template parameter of a primary class template or alias template
2198  // is a template parameter pack, it shall be the last template parameter.
2199  if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2200  (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2201  TPC == TPC_TypeAliasTemplate)) {
2202  Diag((*NewParam)->getLocation(),
2203  diag::err_template_param_pack_must_be_last_template_parameter);
2204  Invalid = true;
2205  }
2206 
2207  if (RedundantDefaultArg) {
2208  // C++ [temp.param]p12:
2209  // A template-parameter shall not be given default arguments
2210  // by two different declarations in the same scope.
2211  Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2212  Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2213  Invalid = true;
2214  } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2215  // C++ [temp.param]p11:
2216  // If a template-parameter of a class template has a default
2217  // template-argument, each subsequent template-parameter shall either
2218  // have a default template-argument supplied or be a template parameter
2219  // pack.
2220  Diag((*NewParam)->getLocation(),
2221  diag::err_template_param_default_arg_missing);
2222  Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2223  Invalid = true;
2224  RemoveDefaultArguments = true;
2225  }
2226 
2227  // If we have an old template parameter list that we're merging
2228  // in, move on to the next parameter.
2229  if (OldParams)
2230  ++OldParam;
2231  }
2232 
2233  // We were missing some default arguments at the end of the list, so remove
2234  // all of the default arguments.
2235  if (RemoveDefaultArguments) {
2236  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2237  NewParamEnd = NewParams->end();
2238  NewParam != NewParamEnd; ++NewParam) {
2239  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2240  TTP->removeDefaultArgument();
2241  else if (NonTypeTemplateParmDecl *NTTP
2242  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2243  NTTP->removeDefaultArgument();
2244  else
2245  cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2246  }
2247  }
2248 
2249  return Invalid;
2250 }
2251 
2252 namespace {
2253 
2254 /// A class which looks for a use of a certain level of template
2255 /// parameter.
2256 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2258 
2259  unsigned Depth;
2260 
2261  // Whether we're looking for a use of a template parameter that makes the
2262  // overall construct type-dependent / a dependent type. This is strictly
2263  // best-effort for now; we may fail to match at all for a dependent type
2264  // in some cases if this is set.
2265  bool IgnoreNonTypeDependent;
2266 
2267  bool Match;
2268  SourceLocation MatchLoc;
2269 
2270  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2271  : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2272  Match(false) {}
2273 
2274  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2275  : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2276  NamedDecl *ND = Params->getParam(0);
2277  if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2278  Depth = PD->getDepth();
2279  } else if (NonTypeTemplateParmDecl *PD =
2280  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2281  Depth = PD->getDepth();
2282  } else {
2283  Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2284  }
2285  }
2286 
2287  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2288  if (ParmDepth >= Depth) {
2289  Match = true;
2290  MatchLoc = Loc;
2291  return true;
2292  }
2293  return false;
2294  }
2295 
2296  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2297  // Prune out non-type-dependent expressions if requested. This can
2298  // sometimes result in us failing to find a template parameter reference
2299  // (if a value-dependent expression creates a dependent type), but this
2300  // mode is best-effort only.
2301  if (auto *E = dyn_cast_or_null<Expr>(S))
2302  if (IgnoreNonTypeDependent && !E->isTypeDependent())
2303  return true;
2304  return super::TraverseStmt(S, Q);
2305  }
2306 
2307  bool TraverseTypeLoc(TypeLoc TL) {
2308  if (IgnoreNonTypeDependent && !TL.isNull() &&
2309  !TL.getType()->isDependentType())
2310  return true;
2311  return super::TraverseTypeLoc(TL);
2312  }
2313 
2314  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2315  return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2316  }
2317 
2318  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2319  // For a best-effort search, keep looking until we find a location.
2320  return IgnoreNonTypeDependent || !Matches(T->getDepth());
2321  }
2322 
2323  bool TraverseTemplateName(TemplateName N) {
2324  if (TemplateTemplateParmDecl *PD =
2325  dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2326  if (Matches(PD->getDepth()))
2327  return false;
2328  return super::TraverseTemplateName(N);
2329  }
2330 
2331  bool VisitDeclRefExpr(DeclRefExpr *E) {
2332  if (NonTypeTemplateParmDecl *PD =
2333  dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2334  if (Matches(PD->getDepth(), E->getExprLoc()))
2335  return false;
2336  return super::VisitDeclRefExpr(E);
2337  }
2338 
2339  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2340  return TraverseType(T->getReplacementType());
2341  }
2342 
2343  bool
2344  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2345  return TraverseTemplateArgument(T->getArgumentPack());
2346  }
2347 
2348  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2349  return TraverseType(T->getInjectedSpecializationType());
2350  }
2351 };
2352 } // end anonymous namespace
2353 
2354 /// Determines whether a given type depends on the given parameter
2355 /// list.
2356 static bool
2358  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2359  Checker.TraverseType(T);
2360  return Checker.Match;
2361 }
2362 
2363 // Find the source range corresponding to the named type in the given
2364 // nested-name-specifier, if any.
2366  QualType T,
2367  const CXXScopeSpec &SS) {
2369  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2370  if (const Type *CurType = NNS->getAsType()) {
2371  if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2372  return NNSLoc.getTypeLoc().getSourceRange();
2373  } else
2374  break;
2375 
2376  NNSLoc = NNSLoc.getPrefix();
2377  }
2378 
2379  return SourceRange();
2380 }
2381 
2382 /// \brief Match the given template parameter lists to the given scope
2383 /// specifier, returning the template parameter list that applies to the
2384 /// name.
2385 ///
2386 /// \param DeclStartLoc the start of the declaration that has a scope
2387 /// specifier or a template parameter list.
2388 ///
2389 /// \param DeclLoc The location of the declaration itself.
2390 ///
2391 /// \param SS the scope specifier that will be matched to the given template
2392 /// parameter lists. This scope specifier precedes a qualified name that is
2393 /// being declared.
2394 ///
2395 /// \param TemplateId The template-id following the scope specifier, if there
2396 /// is one. Used to check for a missing 'template<>'.
2397 ///
2398 /// \param ParamLists the template parameter lists, from the outermost to the
2399 /// innermost template parameter lists.
2400 ///
2401 /// \param IsFriend Whether to apply the slightly different rules for
2402 /// matching template parameters to scope specifiers in friend
2403 /// declarations.
2404 ///
2405 /// \param IsMemberSpecialization will be set true if the scope specifier
2406 /// denotes a fully-specialized type, and therefore this is a declaration of
2407 /// a member specialization.
2408 ///
2409 /// \returns the template parameter list, if any, that corresponds to the
2410 /// name that is preceded by the scope specifier @p SS. This template
2411 /// parameter list may have template parameters (if we're declaring a
2412 /// template) or may have no template parameters (if we're declaring a
2413 /// template specialization), or may be NULL (if what we're declaring isn't
2414 /// itself a template).
2416  SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2417  TemplateIdAnnotation *TemplateId,
2418  ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2419  bool &IsMemberSpecialization, bool &Invalid) {
2420  IsMemberSpecialization = false;
2421  Invalid = false;
2422 
2423  // The sequence of nested types to which we will match up the template
2424  // parameter lists. We first build this list by starting with the type named
2425  // by the nested-name-specifier and walking out until we run out of types.
2426  SmallVector<QualType, 4> NestedTypes;
2427  QualType T;
2428  if (SS.getScopeRep()) {
2429  if (CXXRecordDecl *Record
2430  = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2431  T = Context.getTypeDeclType(Record);
2432  else
2433  T = QualType(SS.getScopeRep()->getAsType(), 0);
2434  }
2435 
2436  // If we found an explicit specialization that prevents us from needing
2437  // 'template<>' headers, this will be set to the location of that
2438  // explicit specialization.
2439  SourceLocation ExplicitSpecLoc;
2440 
2441  while (!T.isNull()) {
2442  NestedTypes.push_back(T);
2443 
2444  // Retrieve the parent of a record type.
2445  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2446  // If this type is an explicit specialization, we're done.
2448  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2449  if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2450  Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2451  ExplicitSpecLoc = Spec->getLocation();
2452  break;
2453  }
2454  } else if (Record->getTemplateSpecializationKind()
2456  ExplicitSpecLoc = Record->getLocation();
2457  break;
2458  }
2459 
2460  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2461  T = Context.getTypeDeclType(Parent);
2462  else
2463  T = QualType();
2464  continue;
2465  }
2466 
2467  if (const TemplateSpecializationType *TST
2469  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2470  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2471  T = Context.getTypeDeclType(Parent);
2472  else
2473  T = QualType();
2474  continue;
2475  }
2476  }
2477 
2478  // Look one step prior in a dependent template specialization type.
2479  if (const DependentTemplateSpecializationType *DependentTST
2481  if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2482  T = QualType(NNS->getAsType(), 0);
2483  else
2484  T = QualType();
2485  continue;
2486  }
2487 
2488  // Look one step prior in a dependent name type.
2489  if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2490  if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2491  T = QualType(NNS->getAsType(), 0);
2492  else
2493  T = QualType();
2494  continue;
2495  }
2496 
2497  // Retrieve the parent of an enumeration type.
2498  if (const EnumType *EnumT = T->getAs<EnumType>()) {
2499  // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2500  // check here.
2501  EnumDecl *Enum = EnumT->getDecl();
2502 
2503  // Get to the parent type.
2504  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2505  T = Context.getTypeDeclType(Parent);
2506  else
2507  T = QualType();
2508  continue;
2509  }
2510 
2511  T = QualType();
2512  }
2513  // Reverse the nested types list, since we want to traverse from the outermost
2514  // to the innermost while checking template-parameter-lists.
2515  std::reverse(NestedTypes.begin(), NestedTypes.end());
2516 
2517  // C++0x [temp.expl.spec]p17:
2518  // A member or a member template may be nested within many
2519  // enclosing class templates. In an explicit specialization for
2520  // such a member, the member declaration shall be preceded by a
2521  // template<> for each enclosing class template that is
2522  // explicitly specialized.
2523  bool SawNonEmptyTemplateParameterList = false;
2524 
2525  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2526  if (SawNonEmptyTemplateParameterList) {
2527  Diag(DeclLoc, diag::err_specialize_member_of_template)
2528  << !Recovery << Range;
2529  Invalid = true;
2530  IsMemberSpecialization = false;
2531  return true;
2532  }
2533 
2534  return false;
2535  };
2536 
2537  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2538  // Check that we can have an explicit specialization here.
2539  if (CheckExplicitSpecialization(Range, true))
2540  return true;
2541 
2542  // We don't have a template header, but we should.
2543  SourceLocation ExpectedTemplateLoc;
2544  if (!ParamLists.empty())
2545  ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2546  else
2547  ExpectedTemplateLoc = DeclStartLoc;
2548 
2549  Diag(DeclLoc, diag::err_template_spec_needs_header)
2550  << Range
2551  << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2552  return false;
2553  };
2554 
2555  unsigned ParamIdx = 0;
2556  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2557  ++TypeIdx) {
2558  T = NestedTypes[TypeIdx];
2559 
2560  // Whether we expect a 'template<>' header.
2561  bool NeedEmptyTemplateHeader = false;
2562 
2563  // Whether we expect a template header with parameters.
2564  bool NeedNonemptyTemplateHeader = false;
2565 
2566  // For a dependent type, the set of template parameters that we
2567  // expect to see.
2568  TemplateParameterList *ExpectedTemplateParams = nullptr;
2569 
2570  // C++0x [temp.expl.spec]p15:
2571  // A member or a member template may be nested within many enclosing
2572  // class templates. In an explicit specialization for such a member, the
2573  // member declaration shall be preceded by a template<> for each
2574  // enclosing class template that is explicitly specialized.
2575  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2577  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2578  ExpectedTemplateParams = Partial->getTemplateParameters();
2579  NeedNonemptyTemplateHeader = true;
2580  } else if (Record->isDependentType()) {
2581  if (Record->getDescribedClassTemplate()) {
2582  ExpectedTemplateParams = Record->getDescribedClassTemplate()
2583  ->getTemplateParameters();
2584  NeedNonemptyTemplateHeader = true;
2585  }
2586  } else if (ClassTemplateSpecializationDecl *Spec
2587  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2588  // C++0x [temp.expl.spec]p4:
2589  // Members of an explicitly specialized class template are defined
2590  // in the same manner as members of normal classes, and not using
2591  // the template<> syntax.
2592  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2593  NeedEmptyTemplateHeader = true;
2594  else
2595  continue;
2596  } else if (Record->getTemplateSpecializationKind()) {
2597  if (Record->getTemplateSpecializationKind()
2599  TypeIdx == NumTypes - 1)
2600  IsMemberSpecialization = true;
2601 
2602  continue;
2603  }
2604  } else if (const TemplateSpecializationType *TST
2606  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2607  ExpectedTemplateParams = Template->getTemplateParameters();
2608  NeedNonemptyTemplateHeader = true;
2609  }
2610  } else if (T->getAs<DependentTemplateSpecializationType>()) {
2611  // FIXME: We actually could/should check the template arguments here
2612  // against the corresponding template parameter list.
2613  NeedNonemptyTemplateHeader = false;
2614  }
2615 
2616  // C++ [temp.expl.spec]p16:
2617  // In an explicit specialization declaration for a member of a class
2618  // template or a member template that ap- pears in namespace scope, the
2619  // member template and some of its enclosing class templates may remain
2620  // unspecialized, except that the declaration shall not explicitly
2621  // specialize a class member template if its en- closing class templates
2622  // are not explicitly specialized as well.
2623  if (ParamIdx < ParamLists.size()) {
2624  if (ParamLists[ParamIdx]->size() == 0) {
2625  if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2626  false))
2627  return nullptr;
2628  } else
2629  SawNonEmptyTemplateParameterList = true;
2630  }
2631 
2632  if (NeedEmptyTemplateHeader) {
2633  // If we're on the last of the types, and we need a 'template<>' header
2634  // here, then it's a member specialization.
2635  if (TypeIdx == NumTypes - 1)
2636  IsMemberSpecialization = true;
2637 
2638  if (ParamIdx < ParamLists.size()) {
2639  if (ParamLists[ParamIdx]->size() > 0) {
2640  // The header has template parameters when it shouldn't. Complain.
2641  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2642  diag::err_template_param_list_matches_nontemplate)
2643  << T
2644  << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2645  ParamLists[ParamIdx]->getRAngleLoc())
2646  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2647  Invalid = true;
2648  return nullptr;
2649  }
2650 
2651  // Consume this template header.
2652  ++ParamIdx;
2653  continue;
2654  }
2655 
2656  if (!IsFriend)
2657  if (DiagnoseMissingExplicitSpecialization(
2658  getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2659  return nullptr;
2660 
2661  continue;
2662  }
2663 
2664  if (NeedNonemptyTemplateHeader) {
2665  // In friend declarations we can have template-ids which don't
2666  // depend on the corresponding template parameter lists. But
2667  // assume that empty parameter lists are supposed to match this
2668  // template-id.
2669  if (IsFriend && T->isDependentType()) {
2670  if (ParamIdx < ParamLists.size() &&
2671  DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2672  ExpectedTemplateParams = nullptr;
2673  else
2674  continue;
2675  }
2676 
2677  if (ParamIdx < ParamLists.size()) {
2678  // Check the template parameter list, if we can.
2679  if (ExpectedTemplateParams &&
2680  !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2681  ExpectedTemplateParams,
2682  true, TPL_TemplateMatch))
2683  Invalid = true;
2684 
2685  if (!Invalid &&
2686  CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2687  TPC_ClassTemplateMember))
2688  Invalid = true;
2689 
2690  ++ParamIdx;
2691  continue;
2692  }
2693 
2694  Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2695  << T
2696  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2697  Invalid = true;
2698  continue;
2699  }
2700  }
2701 
2702  // If there were at least as many template-ids as there were template
2703  // parameter lists, then there are no template parameter lists remaining for
2704  // the declaration itself.
2705  if (ParamIdx >= ParamLists.size()) {
2706  if (TemplateId && !IsFriend) {
2707  // We don't have a template header for the declaration itself, but we
2708  // should.
2709  DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2710  TemplateId->RAngleLoc));
2711 
2712  // Fabricate an empty template parameter list for the invented header.
2714  SourceLocation(), None,
2715  SourceLocation(), nullptr);
2716  }
2717 
2718  return nullptr;
2719  }
2720 
2721  // If there were too many template parameter lists, complain about that now.
2722  if (ParamIdx < ParamLists.size() - 1) {
2723  bool HasAnyExplicitSpecHeader = false;
2724  bool AllExplicitSpecHeaders = true;
2725  for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2726  if (ParamLists[I]->size() == 0)
2727  HasAnyExplicitSpecHeader = true;
2728  else
2729  AllExplicitSpecHeaders = false;
2730  }
2731 
2732  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2733  AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2734  : diag::err_template_spec_extra_headers)
2735  << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2736  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2737 
2738  // If there was a specialization somewhere, such that 'template<>' is
2739  // not required, and there were any 'template<>' headers, note where the
2740  // specialization occurred.
2741  if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2742  Diag(ExplicitSpecLoc,
2743  diag::note_explicit_template_spec_does_not_need_header)
2744  << NestedTypes.back();
2745 
2746  // We have a template parameter list with no corresponding scope, which
2747  // means that the resulting template declaration can't be instantiated
2748  // properly (we'll end up with dependent nodes when we shouldn't).
2749  if (!AllExplicitSpecHeaders)
2750  Invalid = true;
2751  }
2752 
2753  // C++ [temp.expl.spec]p16:
2754  // In an explicit specialization declaration for a member of a class
2755  // template or a member template that ap- pears in namespace scope, the
2756  // member template and some of its enclosing class templates may remain
2757  // unspecialized, except that the declaration shall not explicitly
2758  // specialize a class member template if its en- closing class templates
2759  // are not explicitly specialized as well.
2760  if (ParamLists.back()->size() == 0 &&
2761  CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2762  false))
2763  return nullptr;
2764 
2765  // Return the last template parameter list, which corresponds to the
2766  // entity being declared.
2767  return ParamLists.back();
2768 }
2769 
2771  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2772  Diag(Template->getLocation(), diag::note_template_declared_here)
2773  << (isa<FunctionTemplateDecl>(Template)
2774  ? 0
2775  : isa<ClassTemplateDecl>(Template)
2776  ? 1
2777  : isa<VarTemplateDecl>(Template)
2778  ? 2
2779  : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2780  << Template->getDeclName();
2781  return;
2782  }
2783 
2785  for (OverloadedTemplateStorage::iterator I = OST->begin(),
2786  IEnd = OST->end();
2787  I != IEnd; ++I)
2788  Diag((*I)->getLocation(), diag::note_template_declared_here)
2789  << 0 << (*I)->getDeclName();
2790 
2791  return;
2792  }
2793 }
2794 
2795 static QualType
2797  const SmallVectorImpl<TemplateArgument> &Converted,
2798  SourceLocation TemplateLoc,
2799  TemplateArgumentListInfo &TemplateArgs) {
2800  ASTContext &Context = SemaRef.getASTContext();
2801  switch (BTD->getBuiltinTemplateKind()) {
2802  case BTK__make_integer_seq: {
2803  // Specializations of __make_integer_seq<S, T, N> are treated like
2804  // S<T, 0, ..., N-1>.
2805 
2806  // C++14 [inteseq.intseq]p1:
2807  // T shall be an integer type.
2808  if (!Converted[1].getAsType()->isIntegralType(Context)) {
2809  SemaRef.Diag(TemplateArgs[1].getLocation(),
2810  diag::err_integer_sequence_integral_element_type);
2811  return QualType();
2812  }
2813 
2814  // C++14 [inteseq.make]p1:
2815  // If N is negative the program is ill-formed.
2816  TemplateArgument NumArgsArg = Converted[2];
2817  llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2818  if (NumArgs < 0) {
2819  SemaRef.Diag(TemplateArgs[2].getLocation(),
2820  diag::err_integer_sequence_negative_length);
2821  return QualType();
2822  }
2823 
2824  QualType ArgTy = NumArgsArg.getIntegralType();
2825  TemplateArgumentListInfo SyntheticTemplateArgs;
2826  // The type argument gets reused as the first template argument in the
2827  // synthetic template argument list.
2828  SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2829  // Expand N into 0 ... N-1.
2830  for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2831  I < NumArgs; ++I) {
2832  TemplateArgument TA(Context, I, ArgTy);
2833  SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2834  TA, ArgTy, TemplateArgs[2].getLocation()));
2835  }
2836  // The first template argument will be reused as the template decl that
2837  // our synthetic template arguments will be applied to.
2838  return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2839  TemplateLoc, SyntheticTemplateArgs);
2840  }
2841 
2843  // Specializations of
2844  // __type_pack_element<Index, T_1, ..., T_N>
2845  // are treated like T_Index.
2846  assert(Converted.size() == 2 &&
2847  "__type_pack_element should be given an index and a parameter pack");
2848 
2849  // If the Index is out of bounds, the program is ill-formed.
2850  TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2851  llvm::APSInt Index = IndexArg.getAsIntegral();
2852  assert(Index >= 0 && "the index used with __type_pack_element should be of "
2853  "type std::size_t, and hence be non-negative");
2854  if (Index >= Ts.pack_size()) {
2855  SemaRef.Diag(TemplateArgs[0].getLocation(),
2856  diag::err_type_pack_element_out_of_bounds);
2857  return QualType();
2858  }
2859 
2860  // We simply return the type at index `Index`.
2861  auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2862  return Nth->getAsType();
2863  }
2864  llvm_unreachable("unexpected BuiltinTemplateDecl!");
2865 }
2866 
2867 /// Determine whether this alias template is "enable_if_t".
2868 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2869  return AliasTemplate->getName().equals("enable_if_t");
2870 }
2871 
2872 /// Collect all of the separable terms in the given condition, which
2873 /// might be a conjunction.
2874 ///
2875 /// FIXME: The right answer is to convert the logical expression into
2876 /// disjunctive normal form, so we can find the first failed term
2877 /// within each possible clause.
2878 static void collectConjunctionTerms(Expr *Clause,
2879  SmallVectorImpl<Expr *> &Terms) {
2880  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2881  if (BinOp->getOpcode() == BO_LAnd) {
2882  collectConjunctionTerms(BinOp->getLHS(), Terms);
2883  collectConjunctionTerms(BinOp->getRHS(), Terms);
2884  }
2885 
2886  return;
2887  }
2888 
2889  Terms.push_back(Clause);
2890 }
2891 
2892 // The ranges-v3 library uses an odd pattern of a top-level "||" with
2893 // a left-hand side that is value-dependent but never true. Identify
2894 // the idiom and ignore that term.
2896  // Top-level '||'.
2897  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2898  if (!BinOp) return Cond;
2899 
2900  if (BinOp->getOpcode() != BO_LOr) return Cond;
2901 
2902  // With an inner '==' that has a literal on the right-hand side.
2903  Expr *LHS = BinOp->getLHS();
2904  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
2905  if (!InnerBinOp) return Cond;
2906 
2907  if (InnerBinOp->getOpcode() != BO_EQ ||
2908  !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2909  return Cond;
2910 
2911  // If the inner binary operation came from a macro expansion named
2912  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2913  // of the '||', which is the real, user-provided condition.
2914  SourceLocation Loc = InnerBinOp->getExprLoc();
2915  if (!Loc.isMacroID()) return Cond;
2916 
2917  StringRef MacroName = PP.getImmediateMacroName(Loc);
2918  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2919  return BinOp->getRHS();
2920 
2921  return Cond;
2922 }
2923 
2924 std::pair<Expr *, std::string>
2925 Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2926  Cond = lookThroughRangesV3Condition(PP, Cond);
2927 
2928  // Separate out all of the terms in a conjunction.
2929  SmallVector<Expr *, 4> Terms;
2930  collectConjunctionTerms(Cond, Terms);
2931 
2932  // Determine which term failed.
2933  Expr *FailedCond = nullptr;
2934  for (Expr *Term : Terms) {
2935  Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2936 
2937  // Literals are uninteresting.
2938  if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2939  isa<IntegerLiteral>(TermAsWritten))
2940  continue;
2941 
2942  // The initialization of the parameter from the argument is
2943  // a constant-evaluated context.
2944  EnterExpressionEvaluationContext ConstantEvaluated(
2946 
2947  bool Succeeded;
2948  if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
2949  !Succeeded) {
2950  FailedCond = TermAsWritten;
2951  break;
2952  }
2953  }
2954 
2955  if (!FailedCond) {
2956  if (!AllowTopLevelCond)
2957  return { nullptr, "" };
2958 
2959  FailedCond = Cond->IgnoreParenImpCasts();
2960  }
2961 
2962  std::string Description;
2963  {
2964  llvm::raw_string_ostream Out(Description);
2965  FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
2966  }
2967  return { FailedCond, Description };
2968 }
2969 
2971  SourceLocation TemplateLoc,
2972  TemplateArgumentListInfo &TemplateArgs) {
2975  if (DTN && DTN->isIdentifier())
2976  // When building a template-id where the template-name is dependent,
2977  // assume the template is a type template. Either our assumption is
2978  // correct, or the code is ill-formed and will be diagnosed when the
2979  // dependent name is substituted.
2981  DTN->getQualifier(),
2982  DTN->getIdentifier(),
2983  TemplateArgs);
2984 
2985  TemplateDecl *Template = Name.getAsTemplateDecl();
2986  if (!Template || isa<FunctionTemplateDecl>(Template) ||
2987  isa<VarTemplateDecl>(Template)) {
2988  // We might have a substituted template template parameter pack. If so,
2989  // build a template specialization type for it.
2991  return Context.getTemplateSpecializationType(Name, TemplateArgs);
2992 
2993  Diag(TemplateLoc, diag::err_template_id_not_a_type)
2994  << Name;
2995  NoteAllFoundTemplates(Name);
2996  return QualType();
2997  }
2998 
2999  // Check that the template argument list is well-formed for this
3000  // template.
3002  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3003  false, Converted))
3004  return QualType();
3005 
3006  QualType CanonType;
3007 
3008  bool InstantiationDependent = false;
3009  if (TypeAliasTemplateDecl *AliasTemplate =
3010  dyn_cast<TypeAliasTemplateDecl>(Template)) {
3011  // Find the canonical type for this type alias template specialization.
3012  TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3013  if (Pattern->isInvalidDecl())
3014  return QualType();
3015 
3017  Converted);
3018 
3019  // Only substitute for the innermost template argument list.
3020  MultiLevelTemplateArgumentList TemplateArgLists;
3021  TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3022  unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3023  for (unsigned I = 0; I < Depth; ++I)
3024  TemplateArgLists.addOuterTemplateArguments(None);
3025 
3027  InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3028  if (Inst.isInvalid())
3029  return QualType();
3030 
3031  CanonType = SubstType(Pattern->getUnderlyingType(),
3032  TemplateArgLists, AliasTemplate->getLocation(),
3033  AliasTemplate->getDeclName());
3034  if (CanonType.isNull()) {
3035  // If this was enable_if and we failed to find the nested type
3036  // within enable_if in a SFINAE context, dig out the specific
3037  // enable_if condition that failed and present that instead.
3038  if (isEnableIfAliasTemplate(AliasTemplate)) {
3039  if (auto DeductionInfo = isSFINAEContext()) {
3040  if (*DeductionInfo &&
3041  (*DeductionInfo)->hasSFINAEDiagnostic() &&
3042  (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3043  diag::err_typename_nested_not_found_enable_if &&
3044  TemplateArgs[0].getArgument().getKind()
3046  Expr *FailedCond;
3047  std::string FailedDescription;
3048  std::tie(FailedCond, FailedDescription) =
3049  findFailedBooleanCondition(
3050  TemplateArgs[0].getSourceExpression(),
3051  /*AllowTopLevelCond=*/true);
3052 
3053  // Remove the old SFINAE diagnostic.
3054  PartialDiagnosticAt OldDiag =
3056  (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3057 
3058  // Add a new SFINAE diagnostic specifying which condition
3059  // failed.
3060  (*DeductionInfo)->addSFINAEDiagnostic(
3061  OldDiag.first,
3062  PDiag(diag::err_typename_nested_not_found_requirement)
3063  << FailedDescription
3064  << FailedCond->getSourceRange());
3065  }
3066  }
3067  }
3068 
3069  return QualType();
3070  }
3071  } else if (Name.isDependent() ||
3073  TemplateArgs, InstantiationDependent)) {
3074  // This class template specialization is a dependent
3075  // type. Therefore, its canonical type is another class template
3076  // specialization type that contains all of the converted
3077  // arguments in canonical form. This ensures that, e.g., A<T> and
3078  // A<T, T> have identical types when A is declared as:
3079  //
3080  // template<typename T, typename U = T> struct A;
3081  CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3082 
3083  // This might work out to be a current instantiation, in which
3084  // case the canonical type needs to be the InjectedClassNameType.
3085  //
3086  // TODO: in theory this could be a simple hashtable lookup; most
3087  // changes to CurContext don't change the set of current
3088  // instantiations.
3089  if (isa<ClassTemplateDecl>(Template)) {
3090  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3091  // If we get out to a namespace, we're done.
3092  if (Ctx->isFileContext()) break;
3093 
3094  // If this isn't a record, keep looking.
3095  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3096  if (!Record) continue;
3097 
3098  // Look for one of the two cases with InjectedClassNameTypes
3099  // and check whether it's the same template.
3100  if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3101  !Record->getDescribedClassTemplate())
3102  continue;
3103 
3104  // Fetch the injected class name type and check whether its
3105  // injected type is equal to the type we just built.
3106  QualType ICNT = Context.getTypeDeclType(Record);
3107  QualType Injected = cast<InjectedClassNameType>(ICNT)
3108  ->getInjectedSpecializationType();
3109 
3110  if (CanonType != Injected->getCanonicalTypeInternal())
3111  continue;
3112 
3113  // If so, the canonical type of this TST is the injected
3114  // class name type of the record we just found.
3115  assert(ICNT.isCanonical());
3116  CanonType = ICNT;
3117  break;
3118  }
3119  }
3120  } else if (ClassTemplateDecl *ClassTemplate
3121  = dyn_cast<ClassTemplateDecl>(Template)) {
3122  // Find the class template specialization declaration that
3123  // corresponds to these arguments.
3124  void *InsertPos = nullptr;
3126  = ClassTemplate->findSpecialization(Converted, InsertPos);
3127  if (!Decl) {
3128  // This is the first time we have referenced this class template
3129  // specialization. Create the canonical declaration and add it to
3130  // the set of specializations.
3132  ClassTemplate->getTemplatedDecl()->getTagKind(),
3133  ClassTemplate->getDeclContext(),
3134  ClassTemplate->getTemplatedDecl()->getLocStart(),
3135  ClassTemplate->getLocation(),
3136  ClassTemplate,
3137  Converted, nullptr);
3138  ClassTemplate->AddSpecialization(Decl, InsertPos);
3139  if (ClassTemplate->isOutOfLine())
3140  Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3141  }
3142 
3143  if (Decl->getSpecializationKind() == TSK_Undeclared) {
3144  MultiLevelTemplateArgumentList TemplateArgLists;
3145  TemplateArgLists.addOuterTemplateArguments(Converted);
3146  InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3147  Decl);
3148  }
3149 
3150  // Diagnose uses of this specialization.
3151  (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3152 
3153  CanonType = Context.getTypeDeclType(Decl);
3154  assert(isa<RecordType>(CanonType) &&
3155  "type of non-dependent specialization is not a RecordType");
3156  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3157  CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3158  TemplateArgs);
3159  }
3160 
3161  // Build the fully-sugared type for this class template
3162  // specialization, which refers back to the class template
3163  // specialization we created or found.
3164  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3165 }
3166 
3167 TypeResult
3169  TemplateTy TemplateD, IdentifierInfo *TemplateII,
3170  SourceLocation TemplateIILoc,
3171  SourceLocation LAngleLoc,
3172  ASTTemplateArgsPtr TemplateArgsIn,
3173  SourceLocation RAngleLoc,
3174  bool IsCtorOrDtorName, bool IsClassName) {
3175  if (SS.isInvalid())
3176  return true;
3177 
3178  if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3179  DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3180 
3181  // C++ [temp.res]p3:
3182  // A qualified-id that refers to a type and in which the
3183  // nested-name-specifier depends on a template-parameter (14.6.2)
3184  // shall be prefixed by the keyword typename to indicate that the
3185  // qualified-id denotes a type, forming an
3186  // elaborated-type-specifier (7.1.5.3).
3187  if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3188  Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3189  << SS.getScopeRep() << TemplateII->getName();
3190  // Recover as if 'typename' were specified.
3191  // FIXME: This is not quite correct recovery as we don't transform SS
3192  // into the corresponding dependent form (and we don't diagnose missing
3193  // 'template' keywords within SS as a result).
3194  return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3195  TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3196  TemplateArgsIn, RAngleLoc);
3197  }
3198 
3199  // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3200  // it's not actually allowed to be used as a type in most cases. Because
3201  // we annotate it before we know whether it's valid, we have to check for
3202  // this case here.
3203  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3204  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3205  Diag(TemplateIILoc,
3206  TemplateKWLoc.isInvalid()
3207  ? diag::err_out_of_line_qualified_id_type_names_constructor
3208  : diag::ext_out_of_line_qualified_id_type_names_constructor)
3209  << TemplateII << 0 /*injected-class-name used as template name*/
3210  << 1 /*if any keyword was present, it was 'template'*/;
3211  }
3212  }
3213 
3214  TemplateName Template = TemplateD.get();
3215 
3216  // Translate the parser's template argument list in our AST format.
3217  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3218  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3219 
3220  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3221  QualType T
3223  DTN->getQualifier(),
3224  DTN->getIdentifier(),
3225  TemplateArgs);
3226  // Build type-source information.
3227  TypeLocBuilder TLB;
3231  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3232  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3233  SpecTL.setTemplateNameLoc(TemplateIILoc);
3234  SpecTL.setLAngleLoc(LAngleLoc);
3235  SpecTL.setRAngleLoc(RAngleLoc);
3236  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3237  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3238  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3239  }
3240 
3241  QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3242  if (Result.isNull())
3243  return true;
3244 
3245  // Build type-source information.
3246  TypeLocBuilder TLB;
3248  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3249  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3250  SpecTL.setTemplateNameLoc(TemplateIILoc);
3251  SpecTL.setLAngleLoc(LAngleLoc);
3252  SpecTL.setRAngleLoc(RAngleLoc);
3253  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3254  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3255 
3256  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3257  // constructor or destructor name (in such a case, the scope specifier
3258  // will be attached to the enclosing Decl or Expr node).
3259  if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3260  // Create an elaborated-type-specifier containing the nested-name-specifier.
3261  Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3262  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3264  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3265  }
3266 
3267  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3268 }
3269 
3271  TypeSpecifierType TagSpec,
3272  SourceLocation TagLoc,
3273  CXXScopeSpec &SS,
3274  SourceLocation TemplateKWLoc,
3275  TemplateTy TemplateD,
3276  SourceLocation TemplateLoc,
3277  SourceLocation LAngleLoc,
3278  ASTTemplateArgsPtr TemplateArgsIn,
3279  SourceLocation RAngleLoc) {
3280  TemplateName Template = TemplateD.get();
3281 
3282  // Translate the parser's template argument list in our AST format.
3283  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3284  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3285 
3286  // Determine the tag kind
3288  ElaboratedTypeKeyword Keyword
3290 
3291  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3293  DTN->getQualifier(),
3294  DTN->getIdentifier(),
3295  TemplateArgs);
3296 
3297  // Build type-source information.
3298  TypeLocBuilder TLB;
3301  SpecTL.setElaboratedKeywordLoc(TagLoc);
3302  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3303  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3304  SpecTL.setTemplateNameLoc(TemplateLoc);
3305  SpecTL.setLAngleLoc(LAngleLoc);
3306  SpecTL.setRAngleLoc(RAngleLoc);
3307  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3308  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3309  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3310  }
3311 
3312  if (TypeAliasTemplateDecl *TAT =
3313  dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3314  // C++0x [dcl.type.elab]p2:
3315  // If the identifier resolves to a typedef-name or the simple-template-id
3316  // resolves to an alias template specialization, the
3317  // elaborated-type-specifier is ill-formed.
3318  Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3319  << TAT << NTK_TypeAliasTemplate << TagKind;
3320  Diag(TAT->getLocation(), diag::note_declared_at);
3321  }
3322 
3323  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3324  if (Result.isNull())
3325  return TypeResult(true);
3326 
3327  // Check the tag kind
3328  if (const RecordType *RT = Result->getAs<RecordType>()) {
3329  RecordDecl *D = RT->getDecl();
3330 
3332  assert(Id && "templated class must have an identifier");
3333 
3334  if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3335  TagLoc, Id)) {
3336  Diag(TagLoc, diag::err_use_with_wrong_tag)
3337  << Result
3339  Diag(D->getLocation(), diag::note_previous_use);
3340  }
3341  }
3342 
3343  // Provide source-location information for the template specialization.
3344  TypeLocBuilder TLB;
3346  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3347  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3348  SpecTL.setTemplateNameLoc(TemplateLoc);
3349  SpecTL.setLAngleLoc(LAngleLoc);
3350  SpecTL.setRAngleLoc(RAngleLoc);
3351  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3352  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3353 
3354  // Construct an elaborated type containing the nested-name-specifier (if any)
3355  // and tag keyword.
3356  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3357  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3358  ElabTL.setElaboratedKeywordLoc(TagLoc);
3359  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3360  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3361 }
3362 
3363 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3364  NamedDecl *PrevDecl,
3365  SourceLocation Loc,
3367 
3369 
3371  const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3372  switch (Arg.getKind()) {
3379  return false;
3380 
3381  case TemplateArgument::Type: {
3382  QualType Type = Arg.getAsType();
3383  const TemplateTypeParmType *TPT =
3385  return TPT && !Type.hasQualifiers() &&
3386  TPT->getDepth() == Depth && TPT->getIndex() == Index;
3387  }
3388 
3390  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3391  if (!DRE || !DRE->getDecl())
3392  return false;
3393  const NonTypeTemplateParmDecl *NTTP =
3394  dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3395  return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3396  }
3397 
3399  const TemplateTemplateParmDecl *TTP =
3400  dyn_cast_or_null<TemplateTemplateParmDecl>(
3402  return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3403  }
3404  llvm_unreachable("unexpected kind of template argument");
3405 }
3406 
3409  if (Params->size() != Args.size())
3410  return false;
3411 
3412  unsigned Depth = Params->getDepth();
3413 
3414  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3415  TemplateArgument Arg = Args[I];
3416 
3417  // If the parameter is a pack expansion, the argument must be a pack
3418  // whose only element is a pack expansion.
3419  if (Params->getParam(I)->isParameterPack()) {
3420  if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3421  !Arg.pack_begin()->isPackExpansion())
3422  return false;
3423  Arg = Arg.pack_begin()->getPackExpansionPattern();
3424  }
3425 
3426  if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3427  return false;
3428  }
3429 
3430  return true;
3431 }
3432 
3433 /// Convert the parser's template argument list representation into our form.
3436  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3437  TemplateId.RAngleLoc);
3438  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3439  TemplateId.NumArgs);
3440  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3441  return TemplateArgs;
3442 }
3443 
3444 template<typename PartialSpecDecl>
3445 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3446  if (Partial->getDeclContext()->isDependentContext())
3447  return;
3448 
3449  // FIXME: Get the TDK from deduction in order to provide better diagnostics
3450  // for non-substitution-failure issues?
3451  TemplateDeductionInfo Info(Partial->getLocation());
3452  if (S.isMoreSpecializedThanPrimary(Partial, Info))
3453  return;
3454 
3455  auto *Template = Partial->getSpecializedTemplate();
3456  S.Diag(Partial->getLocation(),
3457  diag::ext_partial_spec_not_more_specialized_than_primary)
3458  << isa<VarTemplateDecl>(Template);
3459 
3460  if (Info.hasSFINAEDiagnostic()) {
3463  Info.takeSFINAEDiagnostic(Diag);
3464  SmallString<128> SFINAEArgString;
3465  Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3466  S.Diag(Diag.first,
3467  diag::note_partial_spec_not_more_specialized_than_primary)
3468  << SFINAEArgString;
3469  }
3470 
3471  S.Diag(Template->getLocation(), diag::note_template_decl_here);
3472 }
3473 
3474 static void
3476  const llvm::SmallBitVector &DeducibleParams) {
3477  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3478  if (!DeducibleParams[I]) {
3479  NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3480  if (Param->getDeclName())
3481  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3482  << Param->getDeclName();
3483  else
3484  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3485  << "(anonymous)";
3486  }
3487  }
3488 }
3489 
3490 
3491 template<typename PartialSpecDecl>
3493  PartialSpecDecl *Partial) {
3494  // C++1z [temp.class.spec]p8: (DR1495)
3495  // - The specialization shall be more specialized than the primary
3496  // template (14.5.5.2).
3497  checkMoreSpecializedThanPrimary(S, Partial);
3498 
3499  // C++ [temp.class.spec]p8: (DR1315)
3500  // - Each template-parameter shall appear at least once in the
3501  // template-id outside a non-deduced context.
3502  // C++1z [temp.class.spec.match]p3 (P0127R2)
3503  // If the template arguments of a partial specialization cannot be
3504  // deduced because of the structure of its template-parameter-list
3505  // and the template-id, the program is ill-formed.
3506  auto *TemplateParams = Partial->getTemplateParameters();
3507  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3508  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3509  TemplateParams->getDepth(), DeducibleParams);
3510 
3511  if (!DeducibleParams.all()) {
3512  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3513  S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3514  << isa<VarTemplatePartialSpecializationDecl>(Partial)
3515  << (NumNonDeducible > 1)
3516  << SourceRange(Partial->getLocation(),
3517  Partial->getTemplateArgsAsWritten()->RAngleLoc);
3518  noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3519  }
3520 }
3521 
3524  checkTemplatePartialSpecialization(*this, Partial);
3525 }
3526 
3529  checkTemplatePartialSpecialization(*this, Partial);
3530 }
3531 
3533  // C++1z [temp.param]p11:
3534  // A template parameter of a deduction guide template that does not have a
3535  // default-argument shall be deducible from the parameter-type-list of the
3536  // deduction guide template.
3537  auto *TemplateParams = TD->getTemplateParameters();
3538  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3539  MarkDeducedTemplateParameters(TD, DeducibleParams);
3540  for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3541  // A parameter pack is deducible (to an empty pack).
3542  auto *Param = TemplateParams->getParam(I);
3543  if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3544  DeducibleParams[I] = true;
3545  }
3546 
3547  if (!DeducibleParams.all()) {
3548  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3549  Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3550  << (NumNonDeducible > 1);
3551  noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3552  }
3553 }
3554 
3556  Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3557  TemplateParameterList *TemplateParams, StorageClass SC,
3558  bool IsPartialSpecialization) {
3559  // D must be variable template id.
3561  "Variable template specialization is declared with a template it.");
3562 
3563  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3564  TemplateArgumentListInfo TemplateArgs =
3565  makeTemplateArgumentListInfo(*this, *TemplateId);
3566  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3567  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3568  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3569 
3570  TemplateName Name = TemplateId->Template.get();
3571 
3572  // The template-id must name a variable template.
3573  VarTemplateDecl *VarTemplate =
3574  dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3575  if (!VarTemplate) {
3576  NamedDecl *FnTemplate;
3577  if (auto *OTS = Name.getAsOverloadedTemplate())
3578  FnTemplate = *OTS->begin();
3579  else
3580  FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3581  if (FnTemplate)
3582  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3583  << FnTemplate->getDeclName();
3584  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3585  << IsPartialSpecialization;
3586  }
3587 
3588  // Check for unexpanded parameter packs in any of the template arguments.
3589  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3590  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3591  UPPC_PartialSpecialization))
3592  return true;
3593 
3594  // Check that the template argument list is well-formed for this
3595  // template.
3597  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3598  false, Converted))
3599  return true;
3600 
3601  // Find the variable template (partial) specialization declaration that
3602  // corresponds to these arguments.
3603  if (IsPartialSpecialization) {
3604  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3605  TemplateArgs.size(), Converted))
3606  return true;
3607 
3608  // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3609  // also do them during instantiation.
3610  bool InstantiationDependent;
3611  if (!Name.isDependent() &&
3613  TemplateArgs.arguments(),
3614  InstantiationDependent)) {
3615  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3616  << VarTemplate->getDeclName();
3617  IsPartialSpecialization = false;
3618  }
3619 
3621  Converted)) {
3622  // C++ [temp.class.spec]p9b3:
3623  //
3624  // -- The argument list of the specialization shall not be identical
3625  // to the implicit argument list of the primary template.
3626  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3627  << /*variable template*/ 1
3628  << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3629  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3630  // FIXME: Recover from this by treating the declaration as a redeclaration
3631  // of the primary template.
3632  return true;
3633  }
3634  }
3635 
3636  void *InsertPos = nullptr;
3637  VarTemplateSpecializationDecl *PrevDecl = nullptr;
3638 
3639  if (IsPartialSpecialization)
3640  // FIXME: Template parameter list matters too
3641  PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3642  else
3643  PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3644 
3645  VarTemplateSpecializationDecl *Specialization = nullptr;
3646 
3647  // Check whether we can declare a variable template specialization in
3648  // the current scope.
3649  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3650  TemplateNameLoc,
3651  IsPartialSpecialization))
3652  return true;
3653 
3654  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3655  // Since the only prior variable template specialization with these
3656  // arguments was referenced but not declared, reuse that
3657  // declaration node as our own, updating its source location and
3658  // the list of outer template parameters to reflect our new declaration.
3659  Specialization = PrevDecl;
3660  Specialization->setLocation(TemplateNameLoc);
3661  PrevDecl = nullptr;
3662  } else if (IsPartialSpecialization) {
3663  // Create a new class template partial specialization declaration node.
3665  cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3668  Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3669  TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3670  Converted, TemplateArgs);
3671 
3672  if (!PrevPartial)
3673  VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3674  Specialization = Partial;
3675 
3676  // If we are providing an explicit specialization of a member variable
3677  // template specialization, make a note of that.
3678  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3679  PrevPartial->setMemberSpecialization();
3680 
3681  CheckTemplatePartialSpecialization(Partial);
3682  } else {
3683  // Create a new class template specialization declaration node for
3684  // this explicit specialization or friend declaration.
3685  Specialization = VarTemplateSpecializationDecl::Create(
3686  Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3687  VarTemplate, DI->getType(), DI, SC, Converted);
3688  Specialization->setTemplateArgsInfo(TemplateArgs);
3689 
3690  if (!PrevDecl)
3691  VarTemplate->AddSpecialization(Specialization, InsertPos);
3692  }
3693 
3694  // C++ [temp.expl.spec]p6:
3695  // If a template, a member template or the member of a class template is
3696  // explicitly specialized then that specialization shall be declared
3697  // before the first use of that specialization that would cause an implicit
3698  // instantiation to take place, in every translation unit in which such a
3699  // use occurs; no diagnostic is required.
3700  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3701  bool Okay = false;
3702  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3703  // Is there any previous explicit specialization declaration?
3705  Okay = true;
3706  break;
3707  }
3708  }
3709 
3710  if (!Okay) {
3711  SourceRange Range(TemplateNameLoc, RAngleLoc);
3712  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3713  << Name << Range;
3714 
3715  Diag(PrevDecl->getPointOfInstantiation(),
3716  diag::note_instantiation_required_here)
3717  << (PrevDecl->getTemplateSpecializationKind() !=
3719  return true;
3720  }
3721  }
3722 
3723  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3724  Specialization->setLexicalDeclContext(CurContext);
3725 
3726  // Add the specialization into its lexical context, so that it can
3727  // be seen when iterating through the list of declarations in that
3728  // context. However, specializations are not found by name lookup.
3729  CurContext->addDecl(Specialization);
3730 
3731  // Note that this is an explicit specialization.
3733 
3734  if (PrevDecl) {
3735  // Check that this isn't a redefinition of this specialization,
3736  // merging with previous declarations.
3737  LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3738  forRedeclarationInCurContext());
3739  PrevSpec.addDecl(PrevDecl);
3740  D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3741  } else if (Specialization->isStaticDataMember() &&
3742  Specialization->isOutOfLine()) {
3743  Specialization->setAccess(VarTemplate->getAccess());
3744  }
3745 
3746  // Link instantiations of static data members back to the template from
3747  // which they were instantiated.
3748  if (Specialization->isStaticDataMember())
3749  Specialization->setInstantiationOfStaticDataMember(
3750  VarTemplate->getTemplatedDecl(),
3751  Specialization->getSpecializationKind());
3752 
3753  return Specialization;
3754 }
3755 
3756 namespace {
3757 /// \brief A partial specialization whose template arguments have matched
3758 /// a given template-id.
3759 struct PartialSpecMatchResult {
3761  TemplateArgumentList *Args;
3762 };
3763 } // end anonymous namespace
3764 
3765 DeclResult
3767  SourceLocation TemplateNameLoc,
3768  const TemplateArgumentListInfo &TemplateArgs) {
3769  assert(Template && "A variable template id without template?");
3770 
3771  // Check that the template argument list is well-formed for this template.
3773  if (CheckTemplateArgumentList(
3774  Template, TemplateNameLoc,
3775  const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3776  Converted))
3777  return true;
3778 
3779  // Find the variable template specialization declaration that
3780  // corresponds to these arguments.
3781  void *InsertPos = nullptr;
3782  if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3783  Converted, InsertPos)) {
3784  checkSpecializationVisibility(TemplateNameLoc, Spec);
3785  // If we already have a variable template specialization, return it.
3786  return Spec;
3787  }
3788 
3789  // This is the first time we have referenced this variable template
3790  // specialization. Create the canonical declaration and add it to
3791  // the set of specializations, based on the closest partial specialization
3792  // that it represents. That is,
3793  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3795  Converted);
3796  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3797  bool AmbiguousPartialSpec = false;
3798  typedef PartialSpecMatchResult MatchResult;
3800  SourceLocation PointOfInstantiation = TemplateNameLoc;
3801  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3802  /*ForTakingAddress=*/false);
3803 
3804  // 1. Attempt to find the closest partial specialization that this
3805  // specializes, if any.
3806  // If any of the template arguments is dependent, then this is probably
3807  // a placeholder for an incomplete declarative context; which must be
3808  // complete by instantiation time. Thus, do not search through the partial
3809  // specializations yet.
3810  // TODO: Unify with InstantiateClassTemplateSpecialization()?
3811  // Perhaps better after unification of DeduceTemplateArguments() and
3812  // getMoreSpecializedPartialSpecialization().
3813  bool InstantiationDependent = false;
3815  TemplateArgs, InstantiationDependent)) {
3816 
3818  Template->getPartialSpecializations(PartialSpecs);
3819 
3820  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3821  VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3822  TemplateDeductionInfo Info(FailedCandidates.getLocation());
3823 
3824  if (TemplateDeductionResult Result =
3825  DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3826  // Store the failed-deduction information for use in diagnostics, later.
3827  // TODO: Actually use the failed-deduction info?
3828  FailedCandidates.addCandidate().set(
3829  DeclAccessPair::make(Template, AS_public), Partial,
3830  MakeDeductionFailureInfo(Context, Result, Info));
3831  (void)Result;
3832  } else {
3833  Matched.push_back(PartialSpecMatchResult());
3834  Matched.back().Partial = Partial;
3835  Matched.back().Args = Info.take();
3836  }
3837  }
3838 
3839  if (Matched.size() >= 1) {
3840  SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3841  if (Matched.size() == 1) {
3842  // -- If exactly one matching specialization is found, the
3843  // instantiation is generated from that specialization.
3844  // We don't need to do anything for this.
3845  } else {
3846  // -- If more than one matching specialization is found, the
3847  // partial order rules (14.5.4.2) are used to determine
3848  // whether one of the specializations is more specialized
3849  // than the others. If none of the specializations is more
3850  // specialized than all of the other matching
3851  // specializations, then the use of the variable template is
3852  // ambiguous and the program is ill-formed.
3853  for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3854  PEnd = Matched.end();
3855  P != PEnd; ++P) {
3856  if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3857  PointOfInstantiation) ==
3858  P->Partial)
3859  Best = P;
3860  }
3861 
3862  // Determine if the best partial specialization is more specialized than
3863  // the others.
3864  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3865  PEnd = Matched.end();
3866  P != PEnd; ++P) {
3867  if (P != Best && getMoreSpecializedPartialSpecialization(
3868  P->Partial, Best->Partial,
3869  PointOfInstantiation) != Best->Partial) {
3870  AmbiguousPartialSpec = true;
3871  break;
3872  }
3873  }
3874  }
3875 
3876  // Instantiate using the best variable template partial specialization.
3877  InstantiationPattern = Best->Partial;
3878  InstantiationArgs = Best->Args;
3879  } else {
3880  // -- If no match is found, the instantiation is generated
3881  // from the primary template.
3882  // InstantiationPattern = Template->getTemplatedDecl();
3883  }
3884  }
3885 
3886  // 2. Create the canonical declaration.
3887  // Note that we do not instantiate a definition until we see an odr-use
3888  // in DoMarkVarDeclReferenced().
3889  // FIXME: LateAttrs et al.?
3890  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3891  Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3892  Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3893  if (!Decl)
3894  return true;
3895 
3896  if (AmbiguousPartialSpec) {
3897  // Partial ordering did not produce a clear winner. Complain.
3898  Decl->setInvalidDecl();
3899  Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3900  << Decl;
3901 
3902  // Print the matching partial specializations.
3903  for (MatchResult P : Matched)
3904  Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3905  << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3906  *P.Args);
3907  return true;
3908  }
3909 
3911  dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3912  Decl->setInstantiationOf(D, InstantiationArgs);
3913 
3914  checkSpecializationVisibility(TemplateNameLoc, Decl);
3915 
3916  assert(Decl && "No variable template specialization?");
3917  return Decl;
3918 }
3919 
3920 ExprResult
3922  const DeclarationNameInfo &NameInfo,
3923  VarTemplateDecl *Template, SourceLocation TemplateLoc,
3924  const TemplateArgumentListInfo *TemplateArgs) {
3925 
3926  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3927  *TemplateArgs);
3928  if (Decl.isInvalid())
3929  return ExprError();
3930 
3931  VarDecl *Var = cast<VarDecl>(Decl.get());
3932  if (!Var->getTemplateSpecializationKind())
3934  NameInfo.getLoc());
3935 
3936  // Build an ordinary singleton decl ref.
3937  return BuildDeclarationNameExpr(SS, NameInfo, Var,
3938  /*FoundD=*/nullptr, TemplateArgs);
3939 }
3940 
3942  SourceLocation TemplateKWLoc,
3943  LookupResult &R,
3944  bool RequiresADL,
3945  const TemplateArgumentListInfo *TemplateArgs) {
3946  // FIXME: Can we do any checking at this point? I guess we could check the
3947  // template arguments that we have against the template name, if the template
3948  // name refers to a single template. That's not a terribly common case,
3949  // though.
3950  // foo<int> could identify a single function unambiguously
3951  // This approach does NOT work, since f<int>(1);
3952  // gets resolved prior to resorting to overload resolution
3953  // i.e., template<class T> void f(double);
3954  // vs template<class T, class U> void f(U);
3955 
3956  // These should be filtered out by our callers.
3957  assert(!R.empty() && "empty lookup results when building templateid");
3958  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3959 
3960  // In C++1y, check variable template ids.
3961  bool InstantiationDependent;
3962  if (R.getAsSingle<VarTemplateDecl>() &&
3964  *TemplateArgs, InstantiationDependent)) {
3965  return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3967  TemplateKWLoc, TemplateArgs);
3968  }
3969 
3970  // We don't want lookup warnings at this point.
3971  R.suppressDiagnostics();
3972 
3975  SS.getWithLocInContext(Context),
3976  TemplateKWLoc,
3977  R.getLookupNameInfo(),
3978  RequiresADL, TemplateArgs,
3979  R.begin(), R.end());
3980 
3981  return ULE;
3982 }
3983 
3984 // We actually only call this from template instantiation.
3985 ExprResult
3987  SourceLocation TemplateKWLoc,
3988  const DeclarationNameInfo &NameInfo,
3989  const TemplateArgumentListInfo *TemplateArgs) {
3990 
3991  assert(TemplateArgs || TemplateKWLoc.isValid());
3992  DeclContext *DC;
3993  if (!(DC = computeDeclContext(SS, false)) ||
3994  DC->isDependentContext() ||
3995  RequireCompleteDeclContext(SS, DC))
3996  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3997 
3998  bool MemberOfUnknownSpecialization;
3999  LookupResult R(*this, NameInfo, LookupOrdinaryName);
4000  LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
4001  MemberOfUnknownSpecialization);
4002 
4003  if (R.isAmbiguous())
4004  return ExprError();
4005 
4006  if (R.empty()) {
4007  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
4008  << NameInfo.getName() << SS.getRange();
4009  return ExprError();
4010  }
4011 
4012  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4013  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4014  << SS.getScopeRep()
4015  << NameInfo.getName().getAsString() << SS.getRange();
4016  Diag(Temp->getLocation(), diag::note_referenced_class_template);
4017  return ExprError();
4018  }
4019 
4020  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4021 }
4022 
4023 /// \brief Form a dependent template name.
4024 ///
4025 /// This action forms a dependent template name given the template
4026 /// name and its (presumably dependent) scope specifier. For
4027 /// example, given "MetaFun::template apply", the scope specifier \p
4028 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4029 /// of the "template" keyword, and "apply" is the \p Name.
4031  CXXScopeSpec &SS,
4032  SourceLocation TemplateKWLoc,
4033  UnqualifiedId &Name,
4034  ParsedType ObjectType,
4035  bool EnteringContext,
4036  TemplateTy &Result,
4037  bool AllowInjectedClassName) {
4038  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4039  Diag(TemplateKWLoc,
4040  getLangOpts().CPlusPlus11 ?
4041  diag::warn_cxx98_compat_template_outside_of_template :
4042  diag::ext_template_outside_of_template)
4043  << FixItHint::CreateRemoval(TemplateKWLoc);
4044 
4045  DeclContext *LookupCtx = nullptr;
4046  if (SS.isSet())
4047  LookupCtx = computeDeclContext(SS, EnteringContext);
4048  if (!LookupCtx && ObjectType)
4049  LookupCtx = computeDeclContext(ObjectType.get());
4050  if (LookupCtx) {
4051  // C++0x [temp.names]p5:
4052  // If a name prefixed by the keyword template is not the name of
4053  // a template, the program is ill-formed. [Note: the keyword
4054  // template may not be applied to non-template members of class
4055  // templates. -end note ] [ Note: as is the case with the
4056  // typename prefix, the template prefix is allowed in cases
4057  // where it is not strictly necessary; i.e., when the
4058  // nested-name-specifier or the expression on the left of the ->
4059  // or . is not dependent on a template-parameter, or the use
4060  // does not appear in the scope of a template. -end note]
4061  //
4062  // Note: C++03 was more strict here, because it banned the use of
4063  // the "template" keyword prior to a template-name that was not a
4064  // dependent name. C++ DR468 relaxed this requirement (the
4065  // "template" keyword is now permitted). We follow the C++0x
4066  // rules, even in C++03 mode with a warning, retroactively applying the DR.
4067  bool MemberOfUnknownSpecialization;
4068  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4069  ObjectType, EnteringContext, Result,
4070  MemberOfUnknownSpecialization);
4071  if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4072  isa<CXXRecordDecl>(LookupCtx) &&
4073  (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4074  cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
4075  // This is a dependent template. Handle it below.
4076  } else if (TNK == TNK_Non_template) {
4077  Diag(Name.getLocStart(),
4078  diag::err_template_kw_refers_to_non_template)
4079  << GetNameFromUnqualifiedId(Name).getName()
4080  << Name.getSourceRange()
4081  << TemplateKWLoc;
4082  return TNK_Non_template;
4083  } else {
4084  // We found something; return it.
4085  auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4086  if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4088  Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4089  // C++14 [class.qual]p2:
4090  // In a lookup in which function names are not ignored and the
4091  // nested-name-specifier nominates a class C, if the name specified
4092  // [...] is the injected-class-name of C, [...] the name is instead
4093  // considered to name the constructor
4094  //
4095  // We don't get here if naming the constructor would be valid, so we
4096  // just reject immediately and recover by treating the
4097  // injected-class-name as naming the template.
4098  Diag(Name.getLocStart(),
4099  diag::ext_out_of_line_qualified_id_type_names_constructor)
4100  << Name.Identifier << 0 /*injected-class-name used as template name*/
4101  << 1 /*'template' keyword was used*/;
4102  }
4103  return TNK;
4104  }
4105  }
4106 
4107  NestedNameSpecifier *Qualifier = SS.getScopeRep();
4108 
4109  switch (Name.getKind()) {
4111  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4112  Name.Identifier));
4114 
4116  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4118  return TNK_Function_template;
4119 
4121  llvm_unreachable("literal operator id cannot have a dependent scope");
4122 
4123  default:
4124  break;
4125  }
4126 
4127  Diag(Name.getLocStart(),
4128  diag::err_template_kw_refers_to_non_template)
4129  << GetNameFromUnqualifiedId(Name).getName()
4130  << Name.getSourceRange()
4131  << TemplateKWLoc;
4132  return TNK_Non_template;
4133 }
4134 
4136  TemplateArgumentLoc &AL,
4137  SmallVectorImpl<TemplateArgument> &Converted) {
4138  const TemplateArgument &Arg = AL.getArgument();
4139  QualType ArgType;
4140  TypeSourceInfo *TSI = nullptr;
4141 
4142  // Check template type parameter.
4143  switch(Arg.getKind()) {
4145  // C++ [temp.arg.type]p1:
4146  // A template-argument for a template-parameter which is a
4147  // type shall be a type-id.
4148  ArgType = Arg.getAsType();
4149  TSI = AL.getTypeSourceInfo();
4150  break;
4152  // We have a template type parameter but the template argument
4153  // is a template without any arguments.
4154  SourceRange SR = AL.getSourceRange();
4155  TemplateName Name = Arg.getAsTemplate();
4156  Diag(SR.getBegin(), diag::err_template_missing_args)
4157  << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
4158  if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4159  Diag(Decl->getLocation(), diag::note_template_decl_here);
4160 
4161  return true;
4162  }
4164  // We have a template type parameter but the template argument is an
4165  // expression; see if maybe it is missing the "typename" keyword.
4166  CXXScopeSpec SS;
4167  DeclarationNameInfo NameInfo;
4168 
4169  if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4170  SS.Adopt(ArgExpr->getQualifierLoc());
4171  NameInfo = ArgExpr->getNameInfo();
4172  } else if (DependentScopeDeclRefExpr *ArgExpr =
4173  dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4174  SS.Adopt(ArgExpr->getQualifierLoc());
4175  NameInfo = ArgExpr->getNameInfo();
4176  } else if (CXXDependentScopeMemberExpr *ArgExpr =
4177  dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4178  if (ArgExpr->isImplicitAccess()) {
4179  SS.Adopt(ArgExpr->getQualifierLoc());
4180  NameInfo = ArgExpr->getMemberNameInfo();
4181  }
4182  }
4183 
4184  if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4185  LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4186  LookupParsedName(Result, CurScope, &SS);
4187 
4188  if (Result.getAsSingle<TypeDecl>() ||
4189  Result.getResultKind() ==
4191  // Suggest that the user add 'typename' before the NNS.
4192  SourceLocation Loc = AL.getSourceRange().getBegin();
4193  Diag(Loc, getLangOpts().MSVCCompat
4194  ? diag::ext_ms_template_type_arg_missing_typename
4195  : diag::err_template_arg_must_be_type_suggest)
4196  << FixItHint::CreateInsertion(Loc, "typename ");
4197  Diag(Param->getLocation(), diag::note_template_param_here);
4198 
4199  // Recover by synthesizing a type using the location information that we
4200  // already have.
4201  ArgType =
4202  Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4203  TypeLocBuilder TLB;
4204  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4205  TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4206  TL.setQualifierLoc(SS.getWithLocInContext(Context));
4207  TL.setNameLoc(NameInfo.getLoc());
4208  TSI = TLB.getTypeSourceInfo(Context, ArgType);
4209 
4210  // Overwrite our input TemplateArgumentLoc so that we can recover
4211  // properly.
4212  AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4214 
4215  break;
4216  }
4217  }
4218  // fallthrough
4219  LLVM_FALLTHROUGH;
4220  }
4221  default: {
4222  // We have a template type parameter but the template argument
4223  // is not a type.
4224  SourceRange SR = AL.getSourceRange();
4225  Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4226  Diag(Param->getLocation(), diag::note_template_param_here);
4227 
4228  return true;
4229  }
4230  }
4231 
4232  if (CheckTemplateArgument(Param, TSI))
4233  return true;
4234 
4235  // Add the converted template type argument.
4236  ArgType = Context.getCanonicalType(ArgType);
4237 
4238  // Objective-C ARC:
4239  // If an explicitly-specified template argument type is a lifetime type
4240  // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4241  if (getLangOpts().ObjCAutoRefCount &&
4242  ArgType->isObjCLifetimeType() &&
4243  !ArgType.getObjCLifetime()) {
4244  Qualifiers Qs;
4246  ArgType = Context.getQualifiedType(ArgType, Qs);
4247  }
4248 
4249  Converted.push_back(TemplateArgument(ArgType));
4250  return false;
4251 }
4252 
4253 /// \brief Substitute template arguments into the default template argument for
4254 /// the given template type parameter.
4255 ///
4256 /// \param SemaRef the semantic analysis object for which we are performing
4257 /// the substitution.
4258 ///
4259 /// \param Template the template that we are synthesizing template arguments
4260 /// for.
4261 ///
4262 /// \param TemplateLoc the location of the template name that started the
4263 /// template-id we are checking.
4264 ///
4265 /// \param RAngleLoc the location of the right angle bracket ('>') that
4266 /// terminates the template-id.
4267 ///
4268 /// \param Param the template template parameter whose default we are
4269 /// substituting into.
4270 ///
4271 /// \param Converted the list of template arguments provided for template
4272 /// parameters that precede \p Param in the template parameter list.
4273 /// \returns the substituted template argument, or NULL if an error occurred.
4274 static TypeSourceInfo *
4276  TemplateDecl *Template,
4277  SourceLocation TemplateLoc,
4278  SourceLocation RAngleLoc,
4279  TemplateTypeParmDecl *Param,
4280  SmallVectorImpl<TemplateArgument> &Converted) {
4281  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4282 
4283  // If the argument type is dependent, instantiate it now based
4284  // on the previously-computed template arguments.
4285  if (ArgType->getType()->isDependentType()) {
4286  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4287  Param, Template, Converted,
4288  SourceRange(TemplateLoc, RAngleLoc));
4289  if (Inst.isInvalid())
4290  return nullptr;
4291 
4292  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4293 
4294  // Only substitute for the innermost template argument list.
4295  MultiLevelTemplateArgumentList TemplateArgLists;
4296  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4297  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4298  TemplateArgLists.addOuterTemplateArguments(None);
4299 
4300  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4301  ArgType =
4302  SemaRef.SubstType(ArgType, TemplateArgLists,
4303  Param->getDefaultArgumentLoc(), Param->getDeclName());
4304  }
4305 
4306  return ArgType;
4307 }
4308 
4309 /// \brief Substitute template arguments into the default template argument for
4310 /// the given non-type template parameter.
4311 ///
4312 /// \param SemaRef the semantic analysis object for which we are performing
4313 /// the substitution.
4314 ///
4315 /// \param Template the template that we are synthesizing template arguments
4316 /// for.
4317 ///
4318 /// \param TemplateLoc the location of the template name that started the
4319 /// template-id we are checking.
4320 ///
4321 /// \param RAngleLoc the location of the right angle bracket ('>') that
4322 /// terminates the template-id.
4323 ///
4324 /// \param Param the non-type template parameter whose default we are
4325 /// substituting into.
4326 ///
4327 /// \param Converted the list of template arguments provided for template
4328 /// parameters that precede \p Param in the template parameter list.
4329 ///
4330 /// \returns the substituted template argument, or NULL if an error occurred.
4331 static ExprResult
4333  TemplateDecl *Template,
4334  SourceLocation TemplateLoc,
4335  SourceLocation RAngleLoc,
4336  NonTypeTemplateParmDecl *Param,
4337  SmallVectorImpl<TemplateArgument> &Converted) {
4338  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4339  Param, Template, Converted,
4340  SourceRange(TemplateLoc, RAngleLoc));
4341  if (Inst.isInvalid())
4342  return ExprError();
4343 
4344  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4345 
4346  // Only substitute for the innermost template argument list.
4347  MultiLevelTemplateArgumentList TemplateArgLists;
4348  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4349  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4350  TemplateArgLists.addOuterTemplateArguments(None);
4351 
4352  EnterExpressionEvaluationContext ConstantEvaluated(
4354  return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4355 }
4356 
4357 /// \brief Substitute template arguments into the default template argument for
4358 /// the given template template parameter.
4359 ///
4360 /// \param SemaRef the semantic analysis object for which we are performing
4361 /// the substitution.
4362 ///
4363 /// \param Template the template that we are synthesizing template arguments
4364 /// for.
4365 ///
4366 /// \param TemplateLoc the location of the template name that started the
4367 /// template-id we are checking.
4368 ///
4369 /// \param RAngleLoc the location of the right angle bracket ('>') that
4370 /// terminates the template-id.
4371 ///
4372 /// \param Param the template template parameter whose default we are
4373 /// substituting into.
4374 ///
4375 /// \param Converted the list of template arguments provided for template
4376 /// parameters that precede \p Param in the template parameter list.
4377 ///
4378 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4379 /// source-location information) that precedes the template name.
4380 ///
4381 /// \returns the substituted template argument, or NULL if an error occurred.
4382 static TemplateName
4384  TemplateDecl *Template,
4385  SourceLocation TemplateLoc,
4386  SourceLocation RAngleLoc,
4387  TemplateTemplateParmDecl *Param,
4389  NestedNameSpecifierLoc &QualifierLoc) {
4391  SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4392  SourceRange(TemplateLoc, RAngleLoc));
4393  if (Inst.isInvalid())
4394  return TemplateName();
4395 
4396  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4397 
4398  // Only substitute for the innermost template argument list.
4399  MultiLevelTemplateArgumentList TemplateArgLists;
4400  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4401  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4402  TemplateArgLists.addOuterTemplateArguments(None);
4403 
4404  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4405  // Substitute into the nested-name-specifier first,
4406  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4407  if (QualifierLoc) {
4408  QualifierLoc =
4409  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4410  if (!QualifierLoc)
4411  return TemplateName();
4412  }
4413 
4414  return SemaRef.SubstTemplateName(
4415  QualifierLoc,
4418  TemplateArgLists);
4419 }
4420 
4421 /// \brief If the given template parameter has a default template
4422 /// argument, substitute into that default template argument and
4423 /// return the corresponding template argument.
4426  SourceLocation TemplateLoc,
4427  SourceLocation RAngleLoc,
4428  Decl *Param,
4430  &Converted,
4431  bool &HasDefaultArg) {
4432  HasDefaultArg = false;
4433 
4434  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4435  if (!hasVisibleDefaultArgument(TypeParm))
4436  return TemplateArgumentLoc();
4437 
4438  HasDefaultArg = true;
4439  TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4440  TemplateLoc,
4441  RAngleLoc,
4442  TypeParm,
4443  Converted);
4444  if (DI)
4445  return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4446 
4447  return TemplateArgumentLoc();
4448  }
4449 
4450  if (NonTypeTemplateParmDecl *NonTypeParm
4451  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4452  if (!hasVisibleDefaultArgument(NonTypeParm))
4453  return TemplateArgumentLoc();
4454 
4455  HasDefaultArg = true;
4456  ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4457  TemplateLoc,
4458  RAngleLoc,
4459  NonTypeParm,
4460  Converted);
4461  if (Arg.isInvalid())
4462  return TemplateArgumentLoc();
4463 
4464  Expr *ArgE = Arg.getAs<Expr>();
4465  return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4466  }
4467 
4468  TemplateTemplateParmDecl *TempTempParm
4469  = cast<TemplateTemplateParmDecl>(Param);
4470  if (!hasVisibleDefaultArgument(TempTempParm))
4471  return TemplateArgumentLoc();
4472 
4473  HasDefaultArg = true;
4474  NestedNameSpecifierLoc QualifierLoc;
4475  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4476  TemplateLoc,
4477  RAngleLoc,
4478  TempTempParm,
4479  Converted,
4480  QualifierLoc);
4481  if (TName.isNull())
4482  return TemplateArgumentLoc();
4483 
4484  return TemplateArgumentLoc(TemplateArgument(TName),
4485  TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4486  TempTempParm->getDefaultArgument().getTemplateNameLoc());
4487 }
4488 
4489 /// Convert a template-argument that we parsed as a type into a template, if
4490 /// possible. C++ permits injected-class-names to perform dual service as
4491 /// template template arguments and as template type arguments.
4493  // Extract and step over any surrounding nested-name-specifier.
4494  NestedNameSpecifierLoc QualLoc;
4495  if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4496  if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4497  return TemplateArgumentLoc();
4498 
4499  QualLoc = ETLoc.getQualifierLoc();
4500  TLoc = ETLoc.getNamedTypeLoc();
4501  }
4502 
4503  // If this type was written as an injected-class-name, it can be used as a
4504  // template template argument.
4505  if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4506  return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4507  QualLoc, InjLoc.getNameLoc());
4508 
4509  // If this type was written as an injected-class-name, it may have been
4510  // converted to a RecordType during instantiation. If the RecordType is
4511  // *not* wrapped in a TemplateSpecializationType and denotes a class
4512  // template specialization, it must have come from an injected-class-name.
4513  if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4514  if (auto *CTSD =
4515  dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4516  return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4517  QualLoc, RecLoc.getNameLoc());
4518 
4519  return TemplateArgumentLoc();
4520 }
4521 
4522 /// \brief Check that the given template argument corresponds to the given
4523 /// template parameter.
4524 ///
4525 /// \param Param The template parameter against which the argument will be
4526 /// checked.
4527 ///
4528 /// \param Arg The template argument, which may be updated due to conversions.
4529 ///
4530 /// \param Template The template in which the template argument resides.
4531 ///
4532 /// \param TemplateLoc The location of the template name for the template
4533 /// whose argument list we're matching.
4534 ///
4535 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4536 /// the template argument list.
4537 ///
4538 /// \param ArgumentPackIndex The index into the argument pack where this
4539 /// argument will be placed. Only valid if the parameter is a parameter pack.
4540 ///
4541 /// \param Converted The checked, converted argument will be added to the
4542 /// end of this small vector.
4543 ///
4544 /// \param CTAK Describes how we arrived at this particular template argument:
4545 /// explicitly written, deduced, etc.
4546 ///
4547 /// \returns true on error, false otherwise.
4549  TemplateArgumentLoc &Arg,
4550  NamedDecl *Template,
4551  SourceLocation TemplateLoc,
4552  SourceLocation RAngleLoc,
4553  unsigned ArgumentPackIndex,
4556  // Check template type parameters.
4557  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4558  return CheckTemplateTypeArgument(TTP, Arg, Converted);
4559 
4560  // Check non-type template parameters.
4561  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4562  // Do substitution on the type of the non-type template parameter
4563  // with the template arguments we've seen thus far. But if the
4564  // template has a dependent context then we cannot substitute yet.
4565  QualType NTTPType = NTTP->getType();
4566  if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4567  NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4568 
4569  if (NTTPType->isDependentType() &&
4570  !isa<TemplateTemplateParmDecl>(Template) &&
4571  !Template->getDeclContext()->isDependentContext()) {
4572  // Do substitution on the type of the non-type template parameter.
4573  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4574  NTTP, Converted,
4575  SourceRange(TemplateLoc, RAngleLoc));
4576  if (Inst.isInvalid())
4577  return true;
4578 
4580  Converted);
4581  NTTPType = SubstType(NTTPType,
4582  MultiLevelTemplateArgumentList(TemplateArgs),
4583  NTTP->getLocation(),
4584  NTTP->getDeclName());
4585  // If that worked, check the non-type template parameter type
4586  // for validity.
4587  if (!NTTPType.isNull())
4588  NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4589  NTTP->getLocation());
4590  if (NTTPType.isNull())
4591  return true;
4592  }
4593 
4594  switch (Arg.getArgument().getKind()) {
4596  llvm_unreachable("Should never see a NULL template argument here");
4597 
4599  TemplateArgument Result;
4600  ExprResult Res =
4601  CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4602  Result, CTAK);
4603  if (Res.isInvalid())
4604  return true;
4605 
4606  // If the resulting expression is new, then use it in place of the
4607  // old expression in the template argument.
4608  if (Res.get() != Arg.getArgument().getAsExpr()) {
4609  TemplateArgument TA(Res.get());
4610  Arg = TemplateArgumentLoc(TA, Res.get());
4611  }
4612 
4613  Converted.push_back(Result);
4614  break;
4615  }
4616 
4620  // We've already checked this template argument, so just copy
4621  // it to the list of converted arguments.
4622  Converted.push_back(Arg.getArgument());
4623  break;
4624 
4627  // We were given a template template argument. It may not be ill-formed;
4628  // see below.
4629  if (DependentTemplateName *DTN
4632  // We have a template argument such as \c T::template X, which we
4633  // parsed as a template template argument. However, since we now
4634  // know that we need a non-type template argument, convert this
4635  // template name into an expression.
4636 
4637  DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4638  Arg.getTemplateNameLoc());
4639 
4640  CXXScopeSpec SS;
4641  SS.Adopt(Arg.getTemplateQualifierLoc());
4642  // FIXME: the template-template arg was a DependentTemplateName,
4643  // so it was provided with a template keyword. However, its source
4644  // location is not stored in the template argument structure.
4645  SourceLocation TemplateKWLoc;
4647  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4648  nullptr);
4649 
4650  // If we parsed the template argument as a pack expansion, create a
4651  // pack expansion expression.
4653  E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4654  if (E.isInvalid())
4655  return true;
4656  }
4657 
4658  TemplateArgument Result;
4659  E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4660  if (E.isInvalid())
4661  return true;
4662 
4663  Converted.push_back(Result);
4664  break;
4665  }
4666 
4667  // We have a template argument that actually does refer to a class
4668  // template, alias template, or template template parameter, and
4669  // therefore cannot be a non-type template argument.
4670  Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4671  << Arg.getSourceRange();
4672 
4673  Diag(Param->getLocation(), diag::note_template_param_here);
4674  return true;
4675 
4676  case TemplateArgument::Type: {
4677  // We have a non-type template parameter but the template
4678  // argument is a type.
4679 
4680  // C++ [temp.arg]p2:
4681  // In a template-argument, an ambiguity between a type-id and
4682  // an expression is resolved to a type-id, regardless of the
4683  // form of the corresponding template-parameter.
4684  //
4685  // We warn specifically about this case, since it can be rather
4686  // confusing for users.
4687  QualType T = Arg.getArgument().getAsType();
4688  SourceRange SR = Arg.getSourceRange();
4689  if (T->isFunctionType())
4690  Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4691  else
4692  Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4693  Diag(Param->getLocation(), diag::note_template_param_here);
4694  return true;
4695  }
4696 
4698  llvm_unreachable("Caller must expand template argument packs");
4699  }
4700 
4701  return false;
4702  }
4703 
4704 
4705  // Check template template parameters.
4706  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4707 
4708  // Substitute into the template parameter list of the template
4709  // template parameter, since previously-supplied template arguments
4710  // may appear within the template template parameter.
4711  {
4712  // Set up a template instantiation context.
4714  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4715  TempParm, Converted,
4716  SourceRange(TemplateLoc, RAngleLoc));
4717  if (Inst.isInvalid())
4718  return true;
4719 
4720  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4721  TempParm = cast_or_null<TemplateTemplateParmDecl>(
4722  SubstDecl(TempParm, CurContext,
4723  MultiLevelTemplateArgumentList(TemplateArgs)));
4724  if (!TempParm)
4725  return true;
4726  }
4727 
4728  // C++1z [temp.local]p1: (DR1004)
4729  // When [the injected-class-name] is used [...] as a template-argument for
4730  // a template template-parameter [...] it refers to the class template
4731  // itself.
4732  if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4734  Arg.getTypeSourceInfo()->getTypeLoc());
4735  if (!ConvertedArg.getArgument().isNull())
4736  Arg = ConvertedArg;
4737  }
4738 
4739  switch (Arg.getArgument().getKind()) {
4741  llvm_unreachable("Should never see a NULL template argument here");
4742 
4745  if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4746  return true;
4747 
4748  Converted.push_back(Arg.getArgument());
4749  break;
4750 
4753  // We have a template template parameter but the template
4754  // argument does not refer to a template.
4755  Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4756  << getLangOpts().CPlusPlus11;
4757  return true;
4758 
4760  llvm_unreachable("Declaration argument with template template parameter");
4762  llvm_unreachable("Integral argument with template template parameter");
4764  llvm_unreachable("Null pointer argument with template template parameter");
4765 
4767  llvm_unreachable("Caller must expand template argument packs");
4768  }
4769 
4770  return false;
4771 }
4772 
4773 /// \brief Diagnose an arity mismatch in the
4774 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4775  SourceLocation TemplateLoc,
4776  TemplateArgumentListInfo &TemplateArgs) {
4777  TemplateParameterList *Params = Template->getTemplateParameters();
4778  unsigned NumParams = Params->size();
4779  unsigned NumArgs = TemplateArgs.size();
4780 
4781  SourceRange Range;
4782  if (NumArgs > NumParams)
4783  Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4784  TemplateArgs.getRAngleLoc());
4785  S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4786  << (NumArgs > NumParams)
4787  << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4788  << Template << Range;
4789  S.Diag(Template->getLocation(), diag::note_template_decl_here)
4790  << Params->getSourceRange();
4791  return true;
4792 }
4793 
4794 /// \brief Check whether the template parameter is a pack expansion, and if so,
4795 /// determine the number of parameters produced by that expansion. For instance:
4796 ///
4797 /// \code
4798 /// template<typename ...Ts> struct A {
4799 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4800 /// };
4801 /// \endcode
4802 ///
4803 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4804 /// is not a pack expansion, so returns an empty Optional.
4806  if (NonTypeTemplateParmDecl *NTTP
4807  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4808  if (NTTP->isExpandedParameterPack())
4809  return NTTP->getNumExpansionTypes();
4810  }
4811 
4812  if (TemplateTemplateParmDecl *TTP
4813  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4814  if (TTP->isExpandedParameterPack())
4815  return TTP->getNumExpansionTemplateParameters();
4816  }
4817 
4818  return None;
4819 }
4820 
4821 /// Diagnose a missing template argument.
4822 template<typename TemplateParmDecl>
4824  TemplateDecl *TD,
4825  const TemplateParmDecl *D,
4826  TemplateArgumentListInfo &Args) {
4827  // Dig out the most recent declaration of the template parameter; there may be
4828  // declarations of the template that are more recent than TD.
4829  D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4830  ->getTemplateParameters()
4831  ->getParam(D->getIndex()));
4832 
4833  // If there's a default argument that's not visible, diagnose that we're
4834  // missing a module import.
4836  if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4837  S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4838  D->getDefaultArgumentLoc(), Modules,
4840  /*Recover*/true);
4841  return true;
4842  }
4843 
4844  // FIXME: If there's a more recent default argument that *is* visible,
4845  // diagnose that it was declared too late.
4846 
4847  return diagnoseArityMismatch(S, TD, Loc, Args);
4848 }
4849 
4850 /// \brief Check that the given template argument list is well-formed
4851 /// for specializing the given template.
4853  TemplateDecl *Template, SourceLocation TemplateLoc,
4854  TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4856  bool UpdateArgsWithConversions) {
4857  // Make a copy of the template arguments for processing. Only make the
4858  // changes at the end when successful in matching the arguments to the
4859  // template.
4860  TemplateArgumentListInfo NewArgs = TemplateArgs;
4861 
4862  // Make sure we get the template parameter list from the most
4863  // recentdeclaration, since that is the only one that has is guaranteed to
4864  // have all the default template argument information.
4865  TemplateParameterList *Params =
4866  cast<TemplateDecl>(Template->getMostRecentDecl())
4867  ->getTemplateParameters();
4868 
4869  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4870 
4871  // C++ [temp.arg]p1:
4872  // [...] The type and form of each template-argument specified in
4873  // a template-id shall match the type and form specified for the
4874  // corresponding parameter declared by the template in its
4875  // template-parameter-list.
4876  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4877  SmallVector<TemplateArgument, 2> ArgumentPack;
4878  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4879  LocalInstantiationScope InstScope(*this, true);
4880  for (TemplateParameterList::iterator Param = Params->begin(),
4881  ParamEnd = Params->end();
4882  Param != ParamEnd; /* increment in loop */) {
4883  // If we have an expanded parameter pack, make sure we don't have too
4884  // many arguments.
4885  if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4886  if (*Expansions == ArgumentPack.size()) {
4887  // We're done with this parameter pack. Pack up its arguments and add
4888  // them to the list.
4889  Converted.push_back(
4890  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4891  ArgumentPack.clear();
4892 
4893  // This argument is assigned to the next parameter.
4894  ++Param;
4895  continue;
4896  } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4897  // Not enough arguments for this parameter pack.
4898  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4899  << false
4900  << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4901  << Template;
4902  Diag(Template->getLocation(), diag::note_template_decl_here)
4903  << Params->getSourceRange();
4904  return true;
4905  }
4906  }
4907 
4908  if (ArgIdx < NumArgs) {
4909  // Check the template argument we were given.
4910  if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4911  TemplateLoc, RAngleLoc,
4912  ArgumentPack.size(), Converted))
4913  return true;
4914 
4915  bool PackExpansionIntoNonPack =
4916  NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4917  (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4918  if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4919  // Core issue 1430: we have a pack expansion as an argument to an
4920  // alias template, and it's not part of a parameter pack. This
4921  // can't be canonicalized, so reject it now.
4922  Diag(NewArgs[ArgIdx].getLocation(),
4923  diag::err_alias_template_expansion_into_fixed_list)
4924  << NewArgs[ArgIdx].getSourceRange();
4925  Diag((*Param)->getLocation(), diag::note_template_param_here);
4926  return true;
4927  }
4928 
4929  // We're now done with this argument.
4930  ++ArgIdx;
4931 
4932  if ((*Param)->isTemplateParameterPack()) {
4933  // The template parameter was a template parameter pack, so take the
4934  // deduced argument and place it on the argument pack. Note that we
4935  // stay on the same template parameter so that we can deduce more
4936  // arguments.
4937  ArgumentPack.push_back(Converted.pop_back_val());
4938  } else {
4939  // Move to the next template parameter.
4940  ++Param;
4941  }
4942 
4943  // If we just saw a pack expansion into a non-pack, then directly convert
4944  // the remaining arguments, because we don't know what parameters they'll
4945  // match up with.
4946  if (PackExpansionIntoNonPack) {
4947  if (!ArgumentPack.empty()) {
4948  // If we were part way through filling in an expanded parameter pack,
4949  // fall back to just producing individual arguments.
4950  Converted.insert(Converted.end(),
4951  ArgumentPack.begin(), ArgumentPack.end());
4952  ArgumentPack.clear();
4953  }
4954 
4955  while (ArgIdx < NumArgs) {
4956  Converted.push_back(NewArgs[ArgIdx].getArgument());
4957  ++ArgIdx;
4958  }
4959 
4960  return false;
4961  }
4962 
4963  continue;
4964  }
4965 
4966  // If we're checking a partial template argument list, we're done.
4967  if (PartialTemplateArgs) {
4968  if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4969  Converted.push_back(
4970  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4971 
4972  return false;
4973  }
4974 
4975  // If we have a template parameter pack with no more corresponding
4976  // arguments, just break out now and we'll fill in the argument pack below.
4977  if ((*Param)->isTemplateParameterPack()) {
4978  assert(!getExpandedPackSize(*Param) &&
4979  "Should have dealt with this already");
4980 
4981  // A non-expanded parameter pack before the end of the parameter list
4982  // only occurs for an ill-formed template parameter list, unless we've
4983  // got a partial argument list for a function template, so just bail out.
4984  if (Param + 1 != ParamEnd)
4985  return true;
4986 
4987  Converted.push_back(
4988  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4989  ArgumentPack.clear();
4990 
4991  ++Param;
4992  continue;
4993  }
4994 
4995  // Check whether we have a default argument.
4996  TemplateArgumentLoc Arg;
4997 
4998  // Retrieve the default template argument from the template
4999  // parameter. For each kind of template parameter, we substitute the
5000  // template arguments provided thus far and any "outer" template arguments
5001  // (when the template parameter was part of a nested template) into
5002  // the default argument.
5003  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5004  if (!hasVisibleDefaultArgument(TTP))
5005  return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5006  NewArgs);
5007 
5009  Template,
5010  TemplateLoc,
5011  RAngleLoc,
5012  TTP,
5013  Converted);
5014  if (!ArgType)
5015  return true;
5016 
5017  Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5018  ArgType);
5019  } else if (NonTypeTemplateParmDecl *NTTP
5020  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5021  if (!hasVisibleDefaultArgument(NTTP))
5022  return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5023  NewArgs);
5024 
5025  ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5026  TemplateLoc,
5027  RAngleLoc,
5028  NTTP,
5029  Converted);
5030  if (E.isInvalid())
5031  return true;
5032 
5033  Expr *Ex = E.getAs<Expr>();
5034  Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5035  } else {
5036  TemplateTemplateParmDecl *TempParm
5037  = cast<TemplateTemplateParmDecl>(*Param);
5038 
5039  if (!hasVisibleDefaultArgument(TempParm))
5040  return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5041  NewArgs);
5042 
5043  NestedNameSpecifierLoc QualifierLoc;
5044  TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5045  TemplateLoc,
5046  RAngleLoc,
5047  TempParm,
5048  Converted,
5049  QualifierLoc);
5050  if (Name.isNull())
5051  return true;
5052 
5053  Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5054  TempParm->getDefaultArgument().getTemplateNameLoc());
5055  }
5056 
5057  // Introduce an instantiation record that describes where we are using
5058  // the default template argument. We're not actually instantiating a
5059  // template here, we just create this object to put a note into the
5060  // context stack.
5061  InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5062  SourceRange(TemplateLoc, RAngleLoc));
5063  if (Inst.isInvalid())
5064  return true;
5065 
5066  // Check the default template argument.
5067  if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5068  RAngleLoc, 0, Converted))
5069  return true;
5070 
5071  // Core issue 150 (assumed resolution): if this is a template template
5072  // parameter, keep track of the default template arguments from the
5073  // template definition.
5074  if (isTemplateTemplateParameter)
5075  NewArgs.addArgument(Arg);
5076 
5077  // Move to the next template parameter and argument.
5078  ++Param;
5079  ++ArgIdx;
5080  }
5081 
5082  // If we're performing a partial argument substitution, allow any trailing
5083  // pack expansions; they might be empty. This can happen even if
5084  // PartialTemplateArgs is false (the list of arguments is complete but
5085  // still dependent).
5086  if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5087  CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5088  while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5089  Converted.push_back(NewArgs[ArgIdx++].getArgument());
5090  }
5091 
5092  // If we have any leftover arguments, then there were too many arguments.
5093  // Complain and fail.
5094  if (ArgIdx < NumArgs)
5095  return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5096 
5097  // No problems found with the new argument list, propagate changes back
5098  // to caller.
5099  if (UpdateArgsWithConversions)
5100  TemplateArgs = std::move(NewArgs);
5101 
5102  return false;
5103 }
5104 
5105 namespace {
5106  class UnnamedLocalNoLinkageFinder
5107  : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5108  {
5109  Sema &S;
5110  SourceRange SR;
5111 
5113 
5114  public:
5115  UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5116 
5117  bool Visit(QualType T) {
5118  return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5119  }
5120 
5121 #define TYPE(Class, Parent) \
5122  bool Visit##Class##Type(const Class##Type *);
5123 #define ABSTRACT_TYPE(Class, Parent) \
5124  bool Visit##Class##Type(const Class##Type *) { return false; }
5125 #define NON_CANONICAL_TYPE(Class, Parent) \
5126  bool Visit##Class##Type(const Class##Type *) { return false; }
5127 #include "clang/AST/TypeNodes.def"
5128 
5129  bool VisitTagDecl(const TagDecl *Tag);
5130  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5131  };
5132 } // end anonymous namespace
5133 
5134 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5135  return false;
5136 }
5137 
5138 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5139  return Visit(T->getElementType());
5140 }
5141 
5142 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5143  return Visit(T->getPointeeType());
5144 }
5145 
5146 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5147  const BlockPointerType* T) {
5148  return Visit(T->getPointeeType());
5149 }
5150 
5151 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5152  const LValueReferenceType* T) {
5153  return Visit(T->getPointeeType());
5154 }
5155 
5156 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5157  const RValueReferenceType* T) {
5158  return Visit(T->getPointeeType());
5159 }
5160 
5161 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5162  const MemberPointerType* T) {
5163  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5164 }
5165 
5166 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5167  const ConstantArrayType* T) {
5168  return Visit(T->getElementType());
5169 }
5170 
5171 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5172  const IncompleteArrayType* T) {
5173  return Visit(T->getElementType());
5174 }
5175 
5176 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5177  const VariableArrayType* T) {
5178  return Visit(T->getElementType());
5179 }
5180 
5181 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5182  const DependentSizedArrayType* T) {
5183  return Visit(T->getElementType());
5184 }
5185 
5186 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5187  const DependentSizedExtVectorType* T) {
5188  return Visit(T->getElementType());
5189 }
5190 
5191 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5192  const DependentAddressSpaceType *T) {
5193  return Visit(T->getPointeeType());
5194 }
5195 
5196 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5197  return Visit(T->getElementType());
5198 }
5199 
5200 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5201  return Visit(T->getElementType());
5202 }
5203 
5204 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5205  const FunctionProtoType* T) {
5206  for (const auto &A : T->param_types()) {
5207  if (Visit(A))
5208  return true;
5209  }
5210 
5211  return Visit(T->getReturnType());
5212 }
5213 
5214 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5215  const FunctionNoProtoType* T) {
5216  return Visit(T->getReturnType());
5217 }
5218 
5219 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5220  const UnresolvedUsingType*) {
5221  return false;
5222 }
5223 
5224 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5225  return false;
5226 }
5227 
5228 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5229  return Visit(T->getUnderlyingType());
5230 }
5231 
5232 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5233  return false;
5234 }
5235 
5236 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5237  const UnaryTransformType*) {
5238  return false;
5239 }
5240 
5241 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5242  return Visit(T->getDeducedType());
5243 }
5244 
5245 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5247  return Visit(T->getDeducedType());
5248 }
5249 
5250 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5251  return VisitTagDecl(T->getDecl());
5252 }
5253 
5254 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5255  return VisitTagDecl(T->getDecl());
5256 }
5257 
5258 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5259  const TemplateTypeParmType*) {
5260  return false;
5261 }
5262 
5263 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5265  return false;
5266 }
5267 
5268 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5269  const TemplateSpecializationType*) {
5270  return false;
5271 }
5272 
5273 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5274  const InjectedClassNameType* T) {
5275  return VisitTagDecl(T->getDecl());
5276 }
5277 
5278 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5279  const DependentNameType* T) {
5280  return VisitNestedNameSpecifier(T->getQualifier());
5281 }
5282 
5283 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5285  return VisitNestedNameSpecifier(T->getQualifier());
5286 }
5287 
5288 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5289  const PackExpansionType* T) {
5290  return Visit(T->getPattern());
5291 }
5292 
5293 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5294  return false;
5295 }
5296 
5297 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5298  const ObjCInterfaceType *) {
5299  return false;
5300 }
5301 
5302 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5303  const ObjCObjectPointerType *) {
5304  return false;
5305 }
5306 
5307 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5308  return Visit(T->getValueType());
5309 }
5310 
5311 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5312  return false;
5313 }
5314 
5315 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5316  if (Tag->getDeclContext()->isFunctionOrMethod()) {
5317  S.Diag(SR.getBegin(),
5318  S.getLangOpts().CPlusPlus11 ?
5319  diag::warn_cxx98_compat_template_arg_local_type :
5320  diag::ext_template_arg_local_type)
5321  << S.Context.getTypeDeclType(Tag) << SR;
5322  return true;
5323  }
5324 
5325  if (!Tag->hasNameForLinkage()) {
5326  S.Diag(SR.getBegin(),
5327  S.getLangOpts().CPlusPlus11 ?
5328  diag::warn_cxx98_compat_template_arg_unnamed_type :
5329  diag::ext_template_arg_unnamed_type) << SR;
5330  S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5331  return true;
5332  }
5333 
5334  return false;
5335 }
5336 
5337 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5338  NestedNameSpecifier *NNS) {
5339  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5340  return true;
5341 
5342  switch (NNS->getKind()) {
5348  return false;
5349 
5352  return Visit(QualType(NNS->getAsType(), 0));
5353  }
5354  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5355 }
5356 
5357 /// \brief Check a template argument against its corresponding
5358 /// template type parameter.
5359 ///
5360 /// This routine implements the semantics of C++ [temp.arg.type]. It
5361 /// returns true if an error occurred, and false otherwise.
5363  TypeSourceInfo *ArgInfo) {
5364  assert(ArgInfo && "invalid TypeSourceInfo");
5365  QualType Arg = ArgInfo->getType();
5366  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5367 
5368  if (Arg->isVariablyModifiedType()) {
5369  return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5370  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5371  return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5372  }
5373 
5374  // C++03 [temp.arg.type]p2:
5375  // A local type, a type with no linkage, an unnamed type or a type
5376  // compounded from any of these types shall not be used as a
5377  // template-argument for a template type-parameter.
5378  //
5379  // C++11 allows these, and even in C++03 we allow them as an extension with
5380  // a warning.
5381  if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5382  UnnamedLocalNoLinkageFinder Finder(*this, SR);
5383  (void)Finder.Visit(Context.getCanonicalType(Arg));
5384  }
5385 
5386  return false;
5387 }
5388 
5393 };
5394 
5395 /// \brief Determine whether the given template argument is a null pointer
5396 /// value of the appropriate type.
5397 static NullPointerValueKind
5399  QualType ParamType, Expr *Arg,
5400  Decl *Entity = nullptr) {
5401  if (Arg->isValueDependent() || Arg->isTypeDependent())
5402  return NPV_NotNullPointer;
5403 
5404  // dllimport'd entities aren't constant but are available inside of template
5405  // arguments.
5406  if (Entity && Entity->hasAttr<DLLImportAttr>())
5407  return NPV_NotNullPointer;
5408 
5409  if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5410  llvm_unreachable(
5411  "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5412 
5413  if (!S.getLangOpts().CPlusPlus11)
5414  return NPV_NotNullPointer;
5415 
5416  // Determine whether we have a constant expression.
5418  if (ArgRV.isInvalid())
5419  return NPV_Error;
5420  Arg = ArgRV.get();
5421 
5422  Expr::EvalResult EvalResult;
5424  EvalResult.Diag = &Notes;
5425  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5426  EvalResult.HasSideEffects) {
5427  SourceLocation DiagLoc = Arg->getExprLoc();
5428 
5429  // If our only note is the usual "invalid subexpression" note, just point
5430  // the caret at its location rather than producing an essentially
5431  // redundant note.
5432  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5433  diag::note_invalid_subexpr_in_const_expr) {
5434  DiagLoc = Notes[0].first;
5435  Notes.clear();
5436  }
5437 
5438  S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5439  << Arg->getType() << Arg->getSourceRange();
5440  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5441  S.Diag(Notes[I].first, Notes[I].second);
5442 
5443  S.Diag(Param->getLocation(), diag::note_template_param_here);
5444  return NPV_Error;
5445  }
5446 
5447  // C++11 [temp.arg.nontype]p1:
5448  // - an address constant expression of type std::nullptr_t
5449  if (Arg->getType()->isNullPtrType())
5450  return NPV_NullPointer;
5451 
5452  // - a constant expression that evaluates to a null pointer value (4.10); or
5453  // - a constant expression that evaluates to a null member pointer value
5454  // (4.11); or
5455  if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5456  (EvalResult.Val.isMemberPointer() &&
5457  !EvalResult.Val.getMemberPointerDecl())) {
5458  // If our expression has an appropriate type, we've succeeded.
5459  bool ObjCLifetimeConversion;
5460  if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5461  S.IsQualificationConversion(Arg->getType(), ParamType, false,
5462  ObjCLifetimeConversion))
5463  return NPV_NullPointer;
5464 
5465  // The types didn't match, but we know we got a null pointer; complain,
5466  // then recover as if the types were correct.
5467  S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5468  << Arg->getType() << ParamType << Arg->getSourceRange();
5469  S.Diag(Param->getLocation(), diag::note_template_param_here);
5470  return NPV_NullPointer;
5471  }
5472 
5473  // If we don't have a null pointer value, but we do have a NULL pointer
5474  // constant, suggest a cast to the appropriate type.
5476  std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5477  S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5478  << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5480  ")");
5481  S.Diag(Param->getLocation(), diag::note_template_param_here);
5482  return NPV_NullPointer;
5483  }
5484 
5485  // FIXME: If we ever want to support general, address-constant expressions
5486  // as non-type template arguments, we should return the ExprResult here to
5487  // be interpreted by the caller.
5488  return NPV_NotNullPointer;
5489 }
5490 
5491 /// \brief Checks whether the given template argument is compatible with its
5492 /// template parameter.
5494  Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5495  Expr *Arg, QualType ArgType) {
5496  bool ObjCLifetimeConversion;
5497  if (ParamType->isPointerType() &&
5498  !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5499  S.IsQualificationConversion(ArgType, ParamType, false,
5500  ObjCLifetimeConversion)) {
5501  // For pointer-to-object types, qualification conversions are
5502  // permitted.
5503  } else {
5504  if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5505  if (!ParamRef->getPointeeType()->isFunctionType()) {
5506  // C++ [temp.arg.nontype]p5b3:
5507  // For a non-type template-parameter of type reference to
5508  // object, no conversions apply. The type referred to by the
5509  // reference may be more cv-qualified than the (otherwise
5510  // identical) type of the template- argument. The
5511  // template-parameter is bound directly to the
5512  // template-argument, which shall be an lvalue.
5513 
5514  // FIXME: Other qualifiers?
5515  unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5516  unsigned ArgQuals = ArgType.getCVRQualifiers();
5517 
5518  if ((ParamQuals | ArgQuals) != ParamQuals) {
5519  S.Diag(Arg->getLocStart(),
5520  diag::err_template_arg_ref_bind_ignores_quals)
5521  << ParamType << Arg->getType() << Arg->getSourceRange();
5522  S.Diag(Param->getLocation(), diag::note_template_param_here);
5523  return true;
5524  }
5525  }
5526  }
5527 
5528  // At this point, the template argument refers to an object or
5529  // function with external linkage. We now need to check whether the
5530  // argument and parameter types are compatible.
5531  if (!S.Context.hasSameUnqualifiedType(ArgType,
5532  ParamType.getNonReferenceType())) {
5533  // We can't perform this conversion or binding.
5534  if (ParamType->isReferenceType())
5535  S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5536  << ParamType << ArgIn->getType() << Arg->getSourceRange();
5537  else
5538  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5539  << ArgIn->getType() << ParamType << Arg->getSourceRange();
5540  S.Diag(Param->getLocation(), diag::note_template_param_here);
5541  return true;
5542  }
5543  }
5544 
5545  return false;
5546 }
5547 
5548 /// \brief Checks whether the given template argument is the address
5549 /// of an object or function according to C++ [temp.arg.nontype]p1.
5550 static bool
5552  NonTypeTemplateParmDecl *Param,
5553  QualType ParamType,
5554  Expr *ArgIn,
5555  TemplateArgument &Converted) {
5556  bool Invalid = false;
5557  Expr *Arg = ArgIn;
5558  QualType ArgType = Arg->getType();
5559 
5560  bool AddressTaken = false;
5561  SourceLocation AddrOpLoc;
5562  if (S.getLangOpts().MicrosoftExt) {
5563  // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5564  // dereference and address-of operators.
5565  Arg = Arg->IgnoreParenCasts();
5566 
5567  bool ExtWarnMSTemplateArg = false;
5568  UnaryOperatorKind FirstOpKind;
5569  SourceLocation FirstOpLoc;
5570  while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5571  UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5572  if (UnOpKind == UO_Deref)
5573  ExtWarnMSTemplateArg = true;
5574  if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5575  Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5576  if (!AddrOpLoc.isValid()) {
5577  FirstOpKind = UnOpKind;
5578  FirstOpLoc = UnOp->getOperatorLoc();
5579  }
5580  } else
5581  break;
5582  }
5583  if (FirstOpLoc.isValid()) {
5584  if (ExtWarnMSTemplateArg)
5585  S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5586  << ArgIn->getSourceRange();
5587 
5588  if (FirstOpKind == UO_AddrOf)
5589  AddressTaken = true;
5590  else if (Arg->getType()->isPointerType()) {
5591  // We cannot let pointers get dereferenced here, that is obviously not a
5592  // constant expression.
5593  assert(FirstOpKind == UO_Deref);
5594  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5595  << Arg->getSourceRange();
5596  }
5597  }
5598  } else {
5599  // See through any implicit casts we added to fix the type.
5600  Arg = Arg->IgnoreImpCasts();
5601 
5602  // C++ [temp.arg.nontype]p1:
5603  //
5604  // A template-argument for a non-type, non-template
5605  // template-parameter shall be one of: [...]
5606  //
5607  // -- the address of an object or function with external
5608  // linkage, including function templates and function
5609  // template-ids but excluding non-static class members,
5610  // expressed as & id-expression where the & is optional if
5611  // the name refers to a function or array, or if the
5612  // corresponding template-parameter is a reference; or
5613 
5614  // In C++98/03 mode, give an extension warning on any extra parentheses.
5615  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5616  bool ExtraParens = false;
5617  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5618  if (!Invalid && !ExtraParens) {
5619  S.Diag(Arg->getLocStart(),
5620  S.getLangOpts().CPlusPlus11
5621  ? diag::warn_cxx98_compat_template_arg_extra_parens
5622  : diag::ext_template_arg_extra_parens)
5623  << Arg->getSourceRange();
5624  ExtraParens = true;
5625  }
5626 
5627  Arg = Parens->getSubExpr();
5628  }
5629 
5630  while (SubstNonTypeTemplateParmExpr *subst =
5631  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5632  Arg = subst->getReplacement()->IgnoreImpCasts();
5633 
5634  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5635  if (UnOp->getOpcode() == UO_AddrOf) {
5636  Arg = UnOp->getSubExpr();
5637  AddressTaken = true;
5638  AddrOpLoc = UnOp->getOperatorLoc();
5639  }
5640  }
5641 
5642  while (SubstNonTypeTemplateParmExpr *subst =
5643  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5644  Arg = subst->getReplacement()->IgnoreImpCasts();
5645  }
5646 
5647  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5648  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5649 
5650  // If our parameter has pointer type, check for a null template value.
5651  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5652  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5653  Entity)) {
5654  case NPV_NullPointer:
5655  S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5656  Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5657  /*isNullPtr=*/true);
5658  return false;
5659 
5660  case NPV_Error:
5661  return true;
5662 
5663  case NPV_NotNullPointer:
5664  break;
5665  }
5666  }
5667 
5668  // Stop checking the precise nature of the argument if it is value dependent,
5669  // it should be checked when instantiated.
5670  if (Arg->isValueDependent()) {
5671  Converted = TemplateArgument(ArgIn);
5672  return false;
5673  }
5674 
5675  if (isa<CXXUuidofExpr>(Arg)) {
5676  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5677  ArgIn, Arg, ArgType))
5678  return true;
5679 
5680  Converted = TemplateArgument(ArgIn);
5681  return false;
5682  }
5683 
5684  if (!DRE) {
5685  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5686  << Arg->getSourceRange();
5687  S.Diag(Param->getLocation(), diag::note_template_param_here);
5688  return true;
5689  }
5690 
5691  // Cannot refer to non-static data members
5692  if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5693  S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5694  << Entity << Arg->getSourceRange();
5695  S.Diag(Param->getLocation(), diag::note_template_param_here);
5696  return true;
5697  }
5698 
5699  // Cannot refer to non-static member functions
5700  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5701  if (!Method->isStatic()) {
5702  S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5703  << Method << Arg->getSourceRange();
5704  S.Diag(Param->getLocation(), diag::note_template_param_here);
5705  return true;
5706  }
5707  }
5708 
5709  FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5710  VarDecl *Var = dyn_cast<VarDecl>(Entity);
5711 
5712  // A non-type template argument must refer to an object or function.
5713  if (!Func && !Var) {
5714  // We found something, but we don't know specifically what it is.
5715  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5716  << Arg->getSourceRange();
5717  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5718  return true;
5719  }
5720 
5721  // Address / reference template args must have external linkage in C++98.
5722  if (Entity->getFormalLinkage() == InternalLinkage) {
5723  S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5724  diag::warn_cxx98_compat_template_arg_object_internal :
5725  diag::ext_template_arg_object_internal)
5726  << !Func << Entity << Arg->getSourceRange();
5727  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5728  << !Func;
5729  } else if (!Entity->hasLinkage()) {
5730  S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5731  << !Func << Entity << Arg->getSourceRange();
5732  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5733  << !Func;
5734  return true;
5735  }
5736 
5737  if (Func) {
5738  // If the template parameter has pointer type, the function decays.
5739  if (ParamType->isPointerType() && !AddressTaken)
5740  ArgType = S.Context.getPointerType(Func->getType());
5741  else if (AddressTaken && ParamType->isReferenceType()) {
5742  // If we originally had an address-of operator, but the
5743  // parameter has reference type, complain and (if things look
5744  // like they will work) drop the address-of operator.
5745  if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5746  ParamType.getNonReferenceType())) {
5747  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5748  << ParamType;
5749  S.Diag(Param->getLocation(), diag::note_template_param_here);
5750  return true;
5751  }
5752 
5753  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5754  << ParamType
5755  << FixItHint::CreateRemoval(AddrOpLoc);
5756  S.Diag(Param->getLocation(), diag::note_template_param_here);
5757 
5758  ArgType = Func->getType();
5759  }
5760  } else {
5761  // A value of reference type is not an object.
5762  if (Var->getType()->isReferenceType()) {
5763  S.Diag(Arg->getLocStart(),
5764  diag::err_template_arg_reference_var)
5765  << Var->getType() << Arg->getSourceRange();
5766  S.Diag(Param->getLocation(), diag::note_template_param_here);
5767  return true;
5768  }
5769 
5770  // A template argument must have static storage duration.
5771  if (Var->getTLSKind()) {
5772  S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5773  << Arg->getSourceRange();
5774  S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5775  return true;
5776  }
5777 
5778  // If the template parameter has pointer type, we must have taken
5779  // the address of this object.
5780  if (ParamType->isReferenceType()) {
5781  if (AddressTaken) {
5782  // If we originally had an address-of operator, but the
5783  // parameter has reference type, complain and (if things look
5784  // like they will work) drop the address-of operator.
5785  if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5786  ParamType.getNonReferenceType())) {
5787  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5788  << ParamType;
5789  S.Diag(Param->getLocation(), diag::note_template_param_here);
5790  return true;
5791  }
5792 
5793  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5794  << ParamType
5795  << FixItHint::CreateRemoval(AddrOpLoc);
5796  S.Diag(Param->getLocation(), diag::note_template_param_here);
5797 
5798  ArgType = Var->getType();
5799  }
5800  } else if (!AddressTaken && ParamType->isPointerType()) {
5801  if (Var->getType()->isArrayType()) {
5802  // Array-to-pointer decay.
5803  ArgType = S.Context.getArrayDecayedType(Var->getType());
5804  } else {
5805  // If the template parameter has pointer type but the address of
5806  // this object was not taken, complain and (possibly) recover by
5807  // taking the address of the entity.
5808  ArgType = S.Context.getPointerType(Var->getType());
5809  if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5810  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5811  << ParamType;
5812  S.Diag(Param->getLocation(), diag::note_template_param_here);
5813  return true;
5814  }
5815 
5816  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5817  << ParamType
5818  << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5819 
5820  S.Diag(Param->getLocation(), diag::note_template_param_here);
5821  }
5822  }
5823  }
5824 
5825  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5826  Arg, ArgType))
5827  return true;
5828 
5829  // Create the template argument.
5830  Converted =
5831  TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5832  S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5833  return false;
5834 }
5835 
5836 /// \brief Checks whether the given template argument is a pointer to
5837 /// member constant according to C++ [temp.arg.nontype]p1.
5839  NonTypeTemplateParmDecl *Param,
5840  QualType ParamType,
5841  Expr *&ResultArg,
5842  TemplateArgument &Converted) {
5843  bool Invalid = false;
5844 
5845  Expr *Arg = ResultArg;
5846  bool ObjCLifetimeConversion;
5847 
5848  // C++ [temp.arg.nontype]p1:
5849  //
5850  // A template-argument for a non-type, non-template
5851  // template-parameter shall be one of: [...]
5852  //
5853  // -- a pointer to member expressed as described in 5.3.1.
5854  DeclRefExpr *DRE = nullptr;
5855 
5856  // In C++98/03 mode, give an extension warning on any extra parentheses.
5857  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5858  bool ExtraParens = false;
5859  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5860  if (!Invalid && !ExtraParens) {
5861  S.Diag(Arg->getLocStart(),
5862  S.getLangOpts().CPlusPlus11 ?
5863  diag::warn_cxx98_compat_template_arg_extra_parens :
5864  diag::ext_template_arg_extra_parens)
5865  << Arg->getSourceRange();
5866  ExtraParens = true;
5867  }
5868 
5869  Arg = Parens->getSubExpr();
5870  }
5871 
5872  while (SubstNonTypeTemplateParmExpr *subst =
5873  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5874  Arg = subst->getReplacement()->IgnoreImpCasts();
5875 
5876  // A pointer-to-member constant written &Class::member.
5877  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5878  if (UnOp->getOpcode() == UO_AddrOf) {
5879  DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5880  if (DRE && !DRE->getQualifier())
5881  DRE = nullptr;
5882  }
5883  }
5884  // A constant of pointer-to-member type.
5885  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5886  if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5887  if (VD->getType()->isMemberPointerType()) {
5888  if (isa<NonTypeTemplateParmDecl>(VD)) {
5889  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5890  Converted = TemplateArgument(Arg);
5891  } else {
5892  VD = cast<ValueDecl>(VD->getCanonicalDecl());
5893  Converted = TemplateArgument(VD, ParamType);
5894  }
5895  return Invalid;
5896  }
5897  }
5898  }
5899 
5900  DRE = nullptr;
5901  }
5902 
5903  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5904 
5905  // Check for a null pointer value.
5906  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5907  Entity)) {
5908  case NPV_Error:
5909  return true;
5910  case NPV_NullPointer:
5911  S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5912  Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5913  /*isNullPtr*/true);
5914  return false;
5915  case NPV_NotNullPointer:
5916  break;
5917  }
5918 
5919  if (S.IsQualificationConversion(ResultArg->getType(),
5920  ParamType.getNonReferenceType(), false,
5921  ObjCLifetimeConversion)) {
5922  ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5923  ResultArg->getValueKind())
5924  .get();
5925  } else if (!S.Context.hasSameUnqualifiedType(
5926  ResultArg->getType(), ParamType.getNonReferenceType())) {
5927  // We can't perform this conversion.
5928  S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
5929  << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
5930  S.Diag(Param->getLocation(), diag::note_template_param_here);
5931  return true;
5932  }
5933 
5934  if (!DRE)
5935  return S.Diag(Arg->getLocStart(),
5936  diag::err_template_arg_not_pointer_to_member_form)
5937  << Arg->getSourceRange();
5938 
5939  if (isa<FieldDecl>(DRE->getDecl()) ||
5940  isa<IndirectFieldDecl>(DRE->getDecl()) ||
5941  isa<CXXMethodDecl>(DRE->getDecl())) {
5942  assert((isa<FieldDecl>(DRE->getDecl()) ||
5943  isa<IndirectFieldDecl>(DRE->getDecl()) ||
5944  !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5945  "Only non-static member pointers can make it here");
5946 
5947  // Okay: this is the address of a non-static member, and therefore
5948  // a member pointer constant.
5949  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5950  Converted = TemplateArgument(Arg);
5951  } else {
5952  ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5953  Converted = TemplateArgument(D, ParamType);
5954  }
5955  return Invalid;
5956  }
5957 
5958  // We found something else, but we don't know specifically what it is.
5959  S.Diag(Arg->getLocStart(),
5960  diag::err_template_arg_not_pointer_to_member_form)
5961  << Arg->getSourceRange();
5962  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5963  return true;
5964 }
5965 
5966 /// \brief Check a template argument against its corresponding
5967 /// non-type template parameter.
5968 ///
5969 /// This routine implements the semantics of C++ [temp.arg.nontype].
5970 /// If an error occurred, it returns ExprError(); otherwise, it
5971 /// returns the converted template argument. \p ParamType is the
5972 /// type of the non-type template parameter after it has been instantiated.
5974  QualType ParamType, Expr *Arg,
5975  TemplateArgument &Converted,
5977  SourceLocation StartLoc = Arg->getLocStart();
5978 
5979  // If the parameter type somehow involves auto, deduce the type now.
5980  if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
5981  // During template argument deduction, we allow 'decltype(auto)' to
5982  // match an arbitrary dependent argument.
5983  // FIXME: The language rules don't say what happens in this case.
5984  // FIXME: We get an opaque dependent type out of decltype(auto) if the
5985  // expression is merely instantiation-dependent; is this enough?
5986  if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5987  auto *AT = dyn_cast<AutoType>(ParamType);
5988  if (AT && AT->isDecltypeAuto()) {
5989  Converted = TemplateArgument(Arg);
5990  return Arg;
5991  }
5992  }
5993 
5994  // When checking a deduced template argument, deduce from its type even if
5995  // the type is dependent, in order to check the types of non-type template
5996  // arguments line up properly in partial ordering.
5998  if (CTAK != CTAK_Specified)
5999  Depth = Param->getDepth() + 1;
6000  if (DeduceAutoType(
6001  Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6002  Arg, ParamType, Depth) == DAR_Failed) {
6003  Diag(Arg->getExprLoc(),
6004  diag::err_non_type_template_parm_type_deduction_failure)
6005  << Param->getDeclName() << Param->getType() << Arg->getType()
6006  << Arg->getSourceRange();
6007  Diag(Param->getLocation(), diag::note_template_param_here);
6008  return ExprError();
6009  }
6010  // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6011  // an error. The error message normally references the parameter
6012  // declaration, but here we'll pass the argument location because that's
6013  // where the parameter type is deduced.
6014  ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6015  if (ParamType.isNull()) {
6016  Diag(Param->getLocation(), diag::note_template_param_here);
6017  return ExprError();
6018  }
6019  }
6020 
6021  // We should have already dropped all cv-qualifiers by now.
6022  assert(!ParamType.hasQualifiers() &&
6023  "non-type template parameter type cannot be qualified");
6024 
6025  if (CTAK == CTAK_Deduced &&
6026  !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6027  Arg->getType())) {
6028  // FIXME: If either type is dependent, we skip the check. This isn't
6029  // correct, since during deduction we're supposed to have replaced each
6030  // template parameter with some unique (non-dependent) placeholder.
6031  // FIXME: If the argument type contains 'auto', we carry on and fail the
6032  // type check in order to force specific types to be more specialized than
6033  // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6034  // work.
6035  if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6036  !Arg->getType()->getContainedAutoType()) {
6037  Converted = TemplateArgument(Arg);
6038  return Arg;
6039  }
6040  // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6041  // we should actually be checking the type of the template argument in P,
6042  // not the type of the template argument deduced from A, against the
6043  // template parameter type.
6044  Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6045  << Arg->getType()
6046  << ParamType.getUnqualifiedType();
6047  Diag(Param->getLocation(), diag::note_template_param_here);
6048  return ExprError();
6049  }
6050 
6051  // If either the parameter has a dependent type or the argument is
6052  // type-dependent, there's nothing we can check now.
6053  if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6054  // FIXME: Produce a cloned, canonical expression?
6055  Converted = TemplateArgument(Arg);
6056  return Arg;
6057  }
6058 
6059  // The initialization of the parameter from the argument is
6060  // a constant-evaluated context.
6061  EnterExpressionEvaluationContext ConstantEvaluated(
6063 
6064  if (getLangOpts().CPlusPlus17) {
6065  // C++17 [temp.arg.nontype]p1:
6066  // A template-argument for a non-type template parameter shall be
6067  // a converted constant expression of the type of the template-parameter.
6068  APValue Value;
6070  Arg, ParamType, Value, CCEK_TemplateArg);
6071  if (ArgResult.isInvalid())
6072  return ExprError();
6073 
6074  // For a value-dependent argument, CheckConvertedConstantExpression is
6075  // permitted (and expected) to be unable to determine a value.
6076  if (ArgResult.get()->isValueDependent()) {
6077  Converted = TemplateArgument(ArgResult.get());
6078  return ArgResult;
6079  }
6080 
6081  QualType CanonParamType = Context.getCanonicalType(ParamType);
6082 
6083  // Convert the APValue to a TemplateArgument.
6084  switch (Value.getKind()) {
6086  assert(ParamType->isNullPtrType());
6087  Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6088  break;
6089  case APValue::Int:
6090  assert(ParamType->isIntegralOrEnumerationType());
6091  Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6092  break;
6093  case APValue::MemberPointer: {
6094  assert(ParamType->isMemberPointerType());
6095 
6096  // FIXME: We need TemplateArgument representation and mangling for these.
6097  if (!Value.getMemberPointerPath().empty()) {
6098  Diag(Arg->getLocStart(),
6099  diag::err_template_arg_member_ptr_base_derived_not_supported)
6100  << Value.getMemberPointerDecl() << ParamType
6101  << Arg->getSourceRange();
6102  return ExprError();
6103  }
6104 
6105  auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6106  Converted = VD ? TemplateArgument(VD, CanonParamType)
6107  : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6108  break;
6109  }
6110  case APValue::LValue: {
6111  // For a non-type template-parameter of pointer or reference type,
6112  // the value of the constant expression shall not refer to
6113  assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6114  ParamType->isNullPtrType());
6115  // -- a temporary object
6116  // -- a string literal
6117  // -- the result of a typeid expression, or
6118  // -- a predefined __func__ variable
6119  if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6120  if (isa<CXXUuidofExpr>(E)) {
6121  Converted = TemplateArgument(const_cast<Expr*>(E));
6122  break;
6123  }
6124  Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6125  << Arg->getSourceRange();
6126  return ExprError();
6127  }
6128  auto *VD = const_cast<ValueDecl *>(
6129  Value.getLValueBase().dyn_cast<const ValueDecl *>());
6130  // -- a subobject
6131  if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6132  VD && VD->getType()->isArrayType() &&
6133  Value.getLValuePath()[0].ArrayIndex == 0 &&
6134  !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6135  // Per defect report (no number yet):
6136  // ... other than a pointer to the first element of a complete array
6137  // object.
6138  } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6139  Value.isLValueOnePastTheEnd()) {
6140  Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6141  << Value.getAsString(Context, ParamType);
6142  return ExprError();
6143  }
6144  assert((VD || !ParamType->isReferenceType()) &&
6145  "null reference should not be a constant expression");
6146  assert((!VD || !ParamType->isNullPtrType()) &&
6147  "non-null value of type nullptr_t?");
6148  Converted = VD ? TemplateArgument(VD, CanonParamType)
6149  : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6150  break;
6151  }
6153  return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6154  case APValue::Float:
6155  case APValue::ComplexInt:
6156  case APValue::ComplexFloat:
6157  case APValue::Vector:
6158  case APValue::Array:
6159  case APValue::Struct:
6160  case APValue::Union:
6161  llvm_unreachable("invalid kind for template argument");
6162  }
6163 
6164  return ArgResult.get();
6165  }
6166 
6167  // C++ [temp.arg.nontype]p5:
6168  // The following conversions are performed on each expression used
6169  // as a non-type template-argument. If a non-type
6170  // template-argument cannot be converted to the type of the
6171  // corresponding template-parameter then the program is
6172  // ill-formed.
6173  if (ParamType->isIntegralOrEnumerationType()) {
6174  // C++11:
6175  // -- for a non-type template-parameter of integral or
6176  // enumeration type, conversions permitted in a converted
6177  // constant expression are applied.
6178  //
6179  // C++98:
6180  // -- for a non-type template-parameter of integral or
6181  // enumeration type, integral promotions (4.5) and integral
6182  // conversions (4.7) are applied.
6183 
6184  if (getLangOpts().CPlusPlus11) {
6185  // C++ [temp.arg.nontype]p1:
6186  // A template-argument for a non-type, non-template template-parameter
6187  // shall be one of:
6188  //
6189  // -- for a non-type template-parameter of integral or enumeration
6190  // type, a converted constant expression of the type of the
6191  // template-parameter; or
6192  llvm::APSInt Value;
6193  ExprResult ArgResult =
6194  CheckConvertedConstantExpression(Arg, ParamType, Value,
6195  CCEK_TemplateArg);
6196  if (ArgResult.isInvalid())
6197  return ExprError();
6198 
6199  // We can't check arbitrary value-dependent arguments.
6200  if (ArgResult.get()->isValueDependent()) {
6201  Converted = TemplateArgument(ArgResult.get());
6202  return ArgResult;
6203  }
6204 
6205  // Widen the argument value to sizeof(parameter type). This is almost
6206  // always a no-op, except when the parameter type is bool. In
6207  // that case, this may extend the argument from 1 bit to 8 bits.
6208  QualType IntegerType = ParamType;
6209  if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6210  IntegerType = Enum->getDecl()->getIntegerType();
6211  Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6212 
6213  Converted = TemplateArgument(Context, Value,
6214  Context.getCanonicalType(ParamType));
6215  return ArgResult;
6216  }
6217 
6218  ExprResult ArgResult = DefaultLvalueConversion(Arg);
6219  if (ArgResult.isInvalid())
6220  return ExprError();
6221  Arg = ArgResult.get();
6222 
6223  QualType ArgType = Arg->getType();
6224 
6225  // C++ [temp.arg.nontype]p1:
6226  // A template-argument for a non-type, non-template
6227  // template-parameter shall be one of:
6228  //
6229  // -- an integral constant-expression of integral or enumeration
6230  // type; or
6231  // -- the name of a non-type template-parameter; or
6232  llvm::APSInt Value;
6233  if (!ArgType->isIntegralOrEnumerationType()) {
6234  Diag(Arg->getLocStart(),
6235  diag::err_template_arg_not_integral_or_enumeral)
6236  << ArgType << Arg->getSourceRange();
6237  Diag(Param->getLocation(), diag::note_template_param_here);
6238  return ExprError();
6239  } else if (!Arg->isValueDependent()) {
6240  class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6241  QualType T;
6242 
6243  public:
6244  TmplArgICEDiagnoser(QualType T) : T(T) { }
6245 
6246  void diagnoseNotICE(Sema &S, SourceLocation Loc,
6247  SourceRange SR) override {
6248  S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6249  }
6250  } Diagnoser(ArgType);
6251 
6252  Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6253  false).get();
6254  if (!Arg)
6255  return ExprError();
6256  }
6257 
6258  // From here on out, all we care about is the unqualified form
6259  // of the argument type.
6260  ArgType = ArgType.getUnqualifiedType();
6261 
6262  // Try to convert the argument to the parameter's type.
6263  if (Context.hasSameType(ParamType, ArgType)) {
6264  // Okay: no conversion necessary
6265  } else if (ParamType->isBooleanType()) {
6266  // This is an integral-to-boolean conversion.
6267  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6268  } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6269  !ParamType->isEnumeralType()) {
6270  // This is an integral promotion or conversion.
6271  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6272  } else {
6273  // We can't perform this conversion.
6274  Diag(Arg->getLocStart(),
6275  diag::err_template_arg_not_convertible)
6276  << Arg->getType() << ParamType << Arg->getSourceRange();
6277  Diag(Param->getLocation(), diag::note_template_param_here);
6278  return ExprError();
6279  }
6280 
6281  // Add the value of this argument to the list of converted
6282  // arguments. We use the bitwidth and signedness of the template
6283  // parameter.
6284  if (Arg->isValueDependent()) {
6285  // The argument is value-dependent. Create a new
6286  // TemplateArgument with the converted expression.
6287  Converted = TemplateArgument(Arg);
6288  return Arg;
6289  }
6290 
6291  QualType IntegerType = Context.getCanonicalType(ParamType);
6292  if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6293  IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6294 
6295  if (ParamType->isBooleanType()) {
6296  // Value must be zero or one.
6297  Value = Value != 0;
6298  unsigned AllowedBits = Context.getTypeSize(IntegerType);
6299  if (Value.getBitWidth() != AllowedBits)
6300  Value = Value.extOrTrunc(AllowedBits);
6301  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6302  } else {
6303  llvm::APSInt OldValue = Value;
6304 
6305  // Coerce the template argument's value to the value it will have
6306  // based on the template parameter's type.
6307  unsigned AllowedBits = Context.getTypeSize(IntegerType);
6308  if (Value.getBitWidth() != AllowedBits)
6309  Value = Value.extOrTrunc(AllowedBits);
6310  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6311 
6312  // Complain if an unsigned parameter received a negative value.
6313  if (IntegerType->isUnsignedIntegerOrEnumerationType()
6314  && (OldValue.isSigned() && OldValue.isNegative())) {
6315  Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6316  << OldValue.toString(10) << Value.toString(10) << Param->getType()
6317  << Arg->getSourceRange();
6318  Diag(Param->getLocation(), diag::note_template_param_here);
6319  }
6320 
6321  // Complain if we overflowed the template parameter's type.
6322  unsigned RequiredBits;
6323  if (IntegerType->isUnsignedIntegerOrEnumerationType())
6324  RequiredBits = OldValue.getActiveBits();
6325  else if (OldValue.isUnsigned())
6326  RequiredBits = OldValue.getActiveBits() + 1;
6327  else
6328  RequiredBits = OldValue.getMinSignedBits();
6329  if (RequiredBits > AllowedBits) {
6330  Diag(Arg->getLocStart(),
6331  diag::warn_template_arg_too_large)
6332  << OldValue.toString(10) << Value.toString(10) << Param->getType()
6333  << Arg->getSourceRange();
6334  Diag(Param->getLocation(), diag::note_template_param_here);
6335  }
6336  }
6337 
6338  Converted = TemplateArgument(Context, Value,
6339  ParamType->isEnumeralType()
6340  ? Context.getCanonicalType(ParamType)
6341  : IntegerType);
6342  return Arg;
6343  }
6344 
6345  QualType ArgType = Arg->getType();
6346  DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6347 
6348  // Handle pointer-to-function, reference-to-function, and
6349  // pointer-to-member-function all in (roughly) the same way.
6350  if (// -- For a non-type template-parameter of type pointer to
6351  // function, only the function-to-pointer conversion (4.3) is
6352  // applied. If the template-argument represents a set of
6353  // overloaded functions (or a pointer to such), the matching
6354  // function is selected from the set (13.4).
6355  (ParamType->isPointerType() &&
6356  ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6357  // -- For a non-type template-parameter of type reference to
6358  // function, no conversions apply. If the template-argument
6359  // represents a set of overloaded functions, the matching
6360  // function is selected from the set (13.4).
6361  (ParamType->isReferenceType() &&
6362  ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6363  // -- For a non-type template-parameter of type pointer to
6364  // member function, no conversions apply. If the
6365  // template-argument represents a set of overloaded member
6366  // functions, the matching member function is selected from
6367  // the set (13.4).
6368  (ParamType->isMemberPointerType() &&
6369  ParamType->getAs<MemberPointerType>()->getPointeeType()
6370  ->isFunctionType())) {
6371 
6372  if (Arg->getType() == Context.OverloadTy) {
6373  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6374  true,
6375  FoundResult)) {
6376  if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6377  return ExprError();
6378 
6379  Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6380  ArgType = Arg->getType();
6381  } else
6382  return ExprError();
6383  }
6384 
6385  if (!ParamType->isMemberPointerType()) {
6387  ParamType,
6388  Arg, Converted))
6389  return ExprError();
6390  return Arg;
6391  }
6392 
6393  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6394  Converted))
6395  return ExprError();
6396  return Arg;
6397  }
6398 
6399  if (ParamType->isPointerType()) {
6400  // -- for a non-type template-parameter of type pointer to
6401  // object, qualification conversions (4.4) and the
6402  // array-to-pointer conversion (4.2) are applied.
6403  // C++0x also allows a value of std::nullptr_t.
6404  assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6405  "Only object pointers allowed here");
6406 
6408  ParamType,
6409  Arg, Converted))
6410  return ExprError();
6411  return Arg;
6412  }
6413 
6414  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6415  // -- For a non-type template-parameter of type reference to
6416  // object, no conversions apply. The type referred to by the
6417  // reference may be more cv-qualified than the (otherwise
6418  // identical) type of the template-argument. The
6419  // template-parameter is bound directly to the
6420  // template-argument, which must be an lvalue.
6421  assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6422  "Only object references allowed here");
6423 
6424  if (Arg->getType() == Context.OverloadTy) {
6425  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6426  ParamRefType->getPointeeType(),
6427  true,
6428  FoundResult)) {
6429  if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6430  return ExprError();
6431 
6432  Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6433  ArgType = Arg->getType();
6434  } else
6435  return ExprError();
6436  }
6437 
6439  ParamType,
6440  Arg, Converted))
6441  return ExprError();
6442  return Arg;
6443  }
6444 
6445  // Deal with parameters of type std::nullptr_t.
6446  if (ParamType->isNullPtrType()) {
6447  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6448  Converted = TemplateArgument(Arg);
6449  return Arg;
6450  }
6451 
6452  switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6453  case NPV_NotNullPointer:
6454  Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6455  << Arg->getType() << ParamType;
6456  Diag(Param->getLocation(), diag::note_template_param_here);
6457  return ExprError();
6458 
6459  case NPV_Error:
6460  return ExprError();
6461 
6462  case NPV_NullPointer:
6463  Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6464  Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6465  /*isNullPtr*/true);
6466  return Arg;
6467  }
6468  }
6469 
6470  // -- For a non-type template-parameter of type pointer to data
6471  // member, qualification conversions (4.4) are applied.
6472  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6473 
6474  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6475  Converted))
6476  return ExprError();
6477  return Arg;
6478 }
6479 
6483 
6484 /// \brief Check a template argument against its corresponding
6485 /// template template parameter.
6486 ///
6487 /// This routine implements the semantics of C++ [temp.arg.template].
6488 /// It returns true if an error occurred, and false otherwise.
6490  TemplateArgumentLoc &Arg,
6491  unsigned ArgumentPackIndex) {
6493  TemplateDecl *Template = Name.getAsTemplateDecl();
6494  if (!Template) {
6495  // Any dependent template name is fine.
6496  assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6497  return false;
6498  }
6499 
6500  if (Template->isInvalidDecl())
6501  return true;
6502 
6503  // C++0x [temp.arg.template]p1:
6504  // A template-argument for a template template-parameter shall be
6505  // the name of a class template or an alias template, expressed as an
6506  // id-expression. When the template-argument names a class template, only
6507  // primary class templates are considered when matching the
6508  // template template argument with the corresponding parameter;
6509  // partial specializations are not considered even if their
6510  // parameter lists match that of the template template parameter.
6511  //
6512  // Note that we also allow template template parameters here, which
6513  // will happen when we are dealing with, e.g., class template
6514  // partial specializations.
6515  if (!isa<ClassTemplateDecl>(Template) &&
6516  !isa<TemplateTemplateParmDecl>(Template) &&
6517  !isa<TypeAliasTemplateDecl>(Template) &&
6518  !isa<BuiltinTemplateDecl>(Template)) {
6519  assert(isa<FunctionTemplateDecl>(Template) &&
6520  "Only function templates are possible here");
6521  Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6522  Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6523  << Template;
6524  }
6525 
6526  TemplateParameterList *Params = Param->getTemplateParameters();
6527  if (Param->isExpandedParameterPack())
6528  Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6529 
6530  // C++1z [temp.arg.template]p3: (DR 150)
6531  // A template-argument matches a template template-parameter P when P
6532  // is at least as specialized as the template-argument A.
6533  if (getLangOpts().RelaxedTemplateTemplateArgs) {
6534  // Quick check for the common case:
6535  // If P contains a parameter pack, then A [...] matches P if each of A's
6536  // template parameters matches the corresponding template parameter in
6537  // the template-parameter-list of P.
6538  if (TemplateParameterListsAreEqual(
6539  Template->getTemplateParameters(), Params, false,
6540  TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6541  return false;
6542 
6543  if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6544  Arg.getLocation()))
6545  return false;
6546  // FIXME: Produce better diagnostics for deduction failures.
6547  }
6548 
6549  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6550  Params,
6551  true,
6552  TPL_TemplateTemplateArgumentMatch,
6553  Arg.getLocation());
6554 }
6555 
6556 /// \brief Given a non-type template argument that refers to a
6557 /// declaration and the type of its corresponding non-type template
6558 /// parameter, produce an expression that properly refers to that
6559 /// declaration.
6560 ExprResult
6562  QualType ParamType,
6563  SourceLocation Loc) {
6564  // C++ [temp.param]p8:
6565  //
6566  // A non-type template-parameter of type "array of T" or
6567  // "function returning T" is adjusted to be of type "pointer to
6568  // T" or "pointer to function returning T", respectively.
6569  if (ParamType->isArrayType())
6570  ParamType = Context.getArrayDecayedType(ParamType);
6571  else if (ParamType->isFunctionType())
6572  ParamType = Context.getPointerType(ParamType);
6573 
6574  // For a NULL non-type template argument, return nullptr casted to the
6575  // parameter's type.
6576  if (Arg.getKind() == TemplateArgument::NullPtr) {
6577  return ImpCastExprToType(
6578  new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6579  ParamType,
6580  ParamType->getAs<MemberPointerType>()
6581  ? CK_NullToMemberPointer
6582  : CK_NullToPointer);
6583  }
6584  assert(Arg.getKind() == TemplateArgument::Declaration &&
6585  "Only declaration template arguments permitted here");
6586 
6587  ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6588 
6589  if (VD->getDeclContext()->isRecord() &&
6590  (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6591  isa<IndirectFieldDecl>(VD))) {
6592  // If the value is a class member, we might have a pointer-to-member.
6593  // Determine whether the non-type template template parameter is of
6594  // pointer-to-member type. If so, we need to build an appropriate
6595  // expression for a pointer-to-member, since a "normal" DeclRefExpr
6596  // would refer to the member itself.
6597  if (ParamType->isMemberPointerType()) {
6598  QualType ClassType
6599  = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6600  NestedNameSpecifier *Qualifier
6601  = NestedNameSpecifier::Create(Context, nullptr, false,
6602  ClassType.getTypePtr());
6603  CXXScopeSpec SS;
6604  SS.MakeTrivial(Context, Qualifier, Loc);
6605 
6606  // The actual value-ness of this is unimportant, but for
6607  // internal consistency's sake, references to instance methods
6608  // are r-values.
6609  ExprValueKind VK = VK_LValue;
6610  if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6611  VK = VK_RValue;
6612 
6613  ExprResult RefExpr = BuildDeclRefExpr(VD,
6614  VD->getType().getNonReferenceType(),
6615  VK,
6616  Loc,
6617  &SS);
6618  if (RefExpr.isInvalid())
6619  return ExprError();
6620 
6621  RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6622 
6623  // We might need to perform a trailing qualification conversion, since
6624  // the element type on the parameter could be more qualified than the
6625  // element type in the expression we constructed.
6626  bool ObjCLifetimeConversion;
6627  if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6628  ParamType.getUnqualifiedType(), false,
6629  ObjCLifetimeConversion))
6630  RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6631 
6632  assert(!RefExpr.isInvalid() &&
6633  Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6634  ParamType.getUnqualifiedType()));
6635  return RefExpr;
6636  }
6637  }
6638 
6639  QualType T = VD->getType().getNonReferenceType();
6640 
6641  if (ParamType->isPointerType()) {
6642  // When the non-type template parameter is a pointer, take the
6643  // address of the declaration.
6644  ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6645  if (RefExpr.isInvalid())
6646  return ExprError();
6647 
6648  if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6649  (T->isFunctionType() || T->isArrayType())) {
6650  // Decay functions and arrays unless we're forming a pointer to array.
6651  RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6652  if (RefExpr.isInvalid())
6653  return ExprError();
6654 
6655  return RefExpr;
6656  }
6657 
6658  // Take the address of everything else
6659  return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6660  }
6661 
6662  ExprValueKind VK = VK_RValue;
6663 
6664  // If the non-type template parameter has reference type, qualify the
6665  // resulting declaration reference with the extra qualifiers on the
6666  // type that the reference refers to.
6667  if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6668  VK = VK_LValue;
6669  T = Context.getQualifiedType(T,
6670  TargetRef->getPointeeType().getQualifiers());
6671  } else if (isa<FunctionDecl>(VD)) {
6672  // References to functions are always lvalues.
6673  VK = VK_LValue;
6674  }
6675 
6676  return BuildDeclRefExpr(VD, T, VK, Loc);
6677 }
6678 
6679 /// \brief Construct a new expression that refers to the given
6680 /// integral template argument with the given source-location
6681 /// information.
6682 ///
6683 /// This routine takes care of the mapping from an integral template
6684 /// argument (which may have any integral type) to the appropriate
6685 /// literal value.
6686 ExprResult
6688  SourceLocation Loc) {
6689  assert(Arg.getKind() == TemplateArgument::Integral &&
6690  "Operation is only valid for integral template arguments");
6691  QualType OrigT = Arg.getIntegralType();
6692 
6693  // If this is an enum type that we're instantiating, we need to use an integer
6694  // type the same size as the enumerator. We don't want to build an
6695  // IntegerLiteral with enum type. The integer type of an enum type can be of
6696  // any integral type with C++11 enum classes, make sure we create the right
6697  // type of literal for it.
6698  QualType T = OrigT;
6699  if (const EnumType *ET = OrigT->getAs<EnumType>())
6700  T = ET->getDecl()->getIntegerType();
6701 
6702  Expr *E;
6703  if (T->isAnyCharacterType()) {
6704  // This does not need to handle u8 character literals because those are
6705  // of type char, and so can also be covered by an ASCII character literal.
6707  if (T->isWideCharType())
6708  Kind = CharacterLiteral::Wide;
6709  else if (T->isChar16Type())
6710  Kind = CharacterLiteral::UTF16;
6711  else if (T->isChar32Type())
6712  Kind = CharacterLiteral::UTF32;
6713  else
6714  Kind = CharacterLiteral::Ascii;
6715 
6716  E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6717  Kind, T, Loc);
6718  } else if (T->isBooleanType()) {
6719  E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6720  T, Loc);
6721  } else if (T->isNullPtrType()) {
6722  E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6723  } else {
6724  E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6725  }
6726 
6727  if (OrigT->isEnumeralType()) {
6728  // FIXME: This is a hack. We need a better way to handle substituted
6729  // non-type template parameters.
6730  E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6731  nullptr,
6732  Context.getTrivialTypeSourceInfo(OrigT, Loc),
6733  Loc, Loc);
6734  }
6735 
6736  return E;
6737 }
6738 
6739 /// \brief Match two template parameters within template parameter lists.
6741  bool Complain,
6743  SourceLocation TemplateArgLoc) {
6744  // Check the actual kind (type, non-type, template).
6745  if (Old->getKind() != New->getKind()) {
6746  if (Complain) {
6747  unsigned NextDiag = diag::err_template_param_different_kind;
6748  if (TemplateArgLoc.isValid()) {
6749  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6750  NextDiag = diag::note_template_param_different_kind;
6751  }
6752  S.Diag(New->getLocation(), NextDiag)
6753  << (Kind != Sema::TPL_TemplateMatch);
6754  S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6755  << (Kind != Sema::TPL_TemplateMatch);
6756  }
6757 
6758  return false;
6759  }
6760 
6761  // Check that both are parameter packs or neither are parameter packs.
6762  // However, if we are matching a template template argument to a
6763  // template template parameter, the template template parameter can have
6764  // a parameter pack where the template template argument does not.
6765  if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6767  Old->isTemplateParameterPack())) {
6768  if (Complain) {
6769  unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6770  if (TemplateArgLoc.isValid()) {
6771  S.Diag(TemplateArgLoc,
6772  diag::err_template_arg_template_params_mismatch);
6773  NextDiag = diag::note_template_parameter_pack_non_pack;
6774  }
6775 
6776  unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6777  : isa<NonTypeTemplateParmDecl>(New)? 1
6778  : 2;
6779  S.Diag(New->getLocation(), NextDiag)
6780  << ParamKind << New->isParameterPack();
6781  S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6782  << ParamKind << Old->isParameterPack();
6783  }
6784 
6785  return false;
6786  }
6787 
6788  // For non-type template parameters, check the type of the parameter.
6789  if (NonTypeTemplateParmDecl *OldNTTP
6790  = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6791  NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6792 
6793  // If we are matching a template template argument to a template
6794  // template parameter and one of the non-type template parameter types
6795  // is dependent, then we must wait until template instantiation time
6796  // to actually compare the arguments.
6798  (OldNTTP->getType()->isDependentType() ||
6799  NewNTTP->getType()->isDependentType()))
6800  return true;
6801 
6802  if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6803  if (Complain) {
6804  unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6805  if (TemplateArgLoc.isValid()) {
6806  S.Diag(TemplateArgLoc,
6807  diag::err_template_arg_template_params_mismatch);
6808  NextDiag = diag::note_template_nontype_parm_different_type;
6809  }
6810  S.Diag(NewNTTP->getLocation(), NextDiag)
6811  << NewNTTP->getType()
6812  << (Kind != Sema::TPL_TemplateMatch);
6813  S.Diag(OldNTTP->getLocation(),
6814  diag::note_template_nontype_parm_prev_declaration)
6815  << OldNTTP->getType();
6816  }
6817 
6818  return false;
6819  }
6820 
6821  return true;
6822  }
6823 
6824  // For template template parameters, check the template parameter types.
6825  // The template parameter lists of template template
6826  // parameters must agree.
6827  if (TemplateTemplateParmDecl *OldTTP
6828  = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6829  TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6831  OldTTP->getTemplateParameters(),
6832  Complain,
6833  (Kind == Sema::TPL_TemplateMatch
6835  : Kind),
6836  TemplateArgLoc);
6837  }
6838 
6839  return true;
6840 }
6841 
6842 /// \brief Diagnose a known arity mismatch when comparing template argument
6843 /// lists.
6844 static
6846  TemplateParameterList *New,
6847  TemplateParameterList *Old,
6849  SourceLocation TemplateArgLoc) {
6850  unsigned NextDiag = diag::err_template_param_list_different_arity;
6851  if (TemplateArgLoc.isValid()) {
6852  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6853  NextDiag = diag::note_template_param_list_different_arity;
6854  }
6855  S.Diag(New->getTemplateLoc(), NextDiag)
6856  << (New->size() > Old->size())
6857  << (Kind != Sema::TPL_TemplateMatch)
6858  << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6859  S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6860  << (Kind != Sema::TPL_TemplateMatch)
6861  << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6862 }
6863 
6864 /// \brief Determine whether the given template parameter lists are
6865 /// equivalent.
6866 ///
6867 /// \param New The new template parameter list, typically written in the
6868 /// source code as part of a new template declaration.
6869 ///
6870 /// \param Old The old template parameter list, typically found via
6871 /// name lookup of the template declared with this template parameter
6872 /// list.
6873 ///
6874 /// \param Complain If true, this routine will produce a diagnostic if
6875 /// the template parameter lists are not equivalent.
6876 ///
6877 /// \param Kind describes how we are to match the template parameter lists.
6878 ///
6879 /// \param TemplateArgLoc If this source location is valid, then we
6880 /// are actually checking the template parameter list of a template
6881 /// argument (New) against the template parameter list of its
6882 /// corresponding template template parameter (Old). We produce
6883 /// slightly different diagnostics in this scenario.
6884 ///
6885 /// \returns True if the template parameter lists are equal, false
6886 /// otherwise.
6887 bool
6889  TemplateParameterList *Old,
6890  bool Complain,
6892  SourceLocation TemplateArgLoc) {
6893  if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6894  if (Complain)
6895  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6896  TemplateArgLoc);
6897 
6898  return false;
6899  }
6900 
6901  // C++0x [temp.arg.template]p3:
6902  // A template-argument matches a template template-parameter (call it P)
6903  // when each of the template parameters in the template-parameter-list of
6904  // the template-argument's corresponding class template or alias template
6905  // (call it A) matches the corresponding template parameter in the
6906  // template-parameter-list of P. [...]
6907  TemplateParameterList::iterator NewParm = New->begin();
6908  TemplateParameterList::iterator NewParmEnd = New->end();
6909  for (TemplateParameterList::iterator OldParm = Old->begin(),
6910  OldParmEnd = Old->end();
6911  OldParm != OldParmEnd; ++OldParm) {
6912  if (Kind != TPL_TemplateTemplateArgumentMatch ||
6913  !(*OldParm)->isTemplateParameterPack()) {
6914  if (NewParm == NewParmEnd) {
6915  if (Complain)
6916  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6917  TemplateArgLoc);
6918 
6919  return false;
6920  }
6921 
6922  if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6923  Kind, TemplateArgLoc))
6924  return false;
6925 
6926  ++NewParm;
6927  continue;
6928  }
6929 
6930  // C++0x [temp.arg.template]p3:
6931  // [...] When P's template- parameter-list contains a template parameter
6932  // pack (14.5.3), the template parameter pack will match zero or more
6933  // template parameters or template parameter packs in the
6934  // template-parameter-list of A with the same type and form as the
6935  // template parameter pack in P (ignoring whether those template
6936  // parameters are template parameter packs).
6937  for (; NewParm != NewParmEnd; ++NewParm) {
6938  if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6939  Kind, TemplateArgLoc))
6940  return false;
6941  }
6942  }
6943 
6944  // Make sure we exhausted all of the arguments.
6945  if (NewParm != NewParmEnd) {
6946  if (Complain)
6947  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6948  TemplateArgLoc);
6949 
6950  return false;
6951  }
6952 
6953  return true;
6954 }
6955 
6956 /// \brief Check whether a template can be declared within this scope.
6957 ///
6958 /// If the template declaration is valid in this scope, returns
6959 /// false. Otherwise, issues a diagnostic and returns true.
6960 bool
6962  if (!S)
6963  return false;
6964 
6965  // Find the nearest enclosing declaration scope.
6966  while ((S->getFlags() & Scope::DeclScope) == 0 ||
6967  (S->getFlags() & Scope::TemplateParamScope) != 0)
6968  S = S->getParent();
6969 
6970  // C++ [temp]p4:
6971  // A template [...] shall not have C linkage.
6972  DeclContext *Ctx = S->getEntity();
6973  if (Ctx && Ctx->isExternCContext()) {
6974  Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6975  << TemplateParams->getSourceRange();
6976  if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6977  Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6978  return true;
6979  }
6980  Ctx = Ctx->getRedeclContext();
6981 
6982  // C++ [temp]p2:
6983  // A template-declaration can appear only as a namespace scope or
6984  // class scope declaration.
6985  if (Ctx) {
6986  if (Ctx->isFileContext())
6987  return false;
6988  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6989  // C++ [temp.mem]p2:
6990  // A local class shall not have member templates.
6991  if (RD->isLocalClass())
6992  return Diag(TemplateParams->getTemplateLoc(),
6993  diag::err_template_inside_local_class)
6994  << TemplateParams->getSourceRange();
6995  else
6996  return false;
6997  }
6998  }
6999 
7000  return Diag(TemplateParams->getTemplateLoc(),
7001  diag::err_template_outside_namespace_or_class_scope)
7002  << TemplateParams->getSourceRange();
7003 }
7004 
7005 /// \brief Determine what kind of template specialization the given declaration
7006 /// is.
7008  if (!D)
7009  return TSK_Undeclared;
7010 
7011  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7012  return Record->getTemplateSpecializationKind();
7013  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7014  return Function->getTemplateSpecializationKind();
7015  if (VarDecl *Var = dyn_cast<VarDecl>(D))
7016  return Var->getTemplateSpecializationKind();
7017 
7018  return TSK_Undeclared;
7019 }
7020 
7021 /// \brief Check whether a specialization is well-formed in the current
7022 /// context.
7023 ///
7024 /// This routine determines whether a template specialization can be declared
7025 /// in the current context (C++ [temp.expl.spec]p2).
7026 ///
7027 /// \param S the semantic analysis object for which this check is being
7028 /// performed.
7029 ///
7030 /// \param Specialized the entity being specialized or instantiated, which
7031 /// may be a kind of template (class template, function template, etc.) or
7032 /// a member of a class template (member function, static data member,
7033 /// member class).
7034 ///
7035 /// \param PrevDecl the previous declaration of this entity, if any.
7036 ///
7037 /// \param Loc the location of the explicit specialization or instantiation of
7038 /// this entity.
7039 ///
7040 /// \param IsPartialSpecialization whether this is a partial specialization of
7041 /// a class template.
7042 ///
7043 /// \returns true if there was an error that we cannot recover from, false
7044 /// otherwise.
7046  NamedDecl *Specialized,
7047  NamedDecl *PrevDecl,
7048  SourceLocation Loc,
7049  bool IsPartialSpecialization) {
7050  // Keep these "kind" numbers in sync with the %select statements in the
7051  // various diagnostics emitted by this routine.
7052  int EntityKind = 0;
7053  if (isa<ClassTemplateDecl>(Specialized))
7054  EntityKind = IsPartialSpecialization? 1 : 0;
7055  else if (isa<VarTemplateDecl>(Specialized))
7056  EntityKind = IsPartialSpecialization ? 3 : 2;
7057  else if (isa<FunctionTemplateDecl>(Specialized))
7058  EntityKind = 4;
7059  else if (isa<CXXMethodDecl>(Specialized))
7060  EntityKind = 5;
7061  else if (isa<VarDecl>(Specialized))
7062  EntityKind = 6;
7063  else if (isa<RecordDecl>(Specialized))
7064  EntityKind = 7;
7065  else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7066  EntityKind = 8;
7067  else {
7068  S.Diag(Loc, diag::err_template_spec_unknown_kind)
7069  << S.getLangOpts().CPlusPlus11;
7070  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7071  return true;
7072  }
7073 
7074  // C++ [temp.expl.spec]p2:
7075  // An explicit specialization shall be declared in the namespace
7076  // of which the template is a member, or, for member templates, in
7077  // the namespace of which the enclosing class or enclosing class
7078  // template is a member. An explicit specialization of a member
7079  // function, member class or static data member of a class
7080  // template shall be declared in the namespace of which the class
7081  // template is a member. Such a declaration may also be a
7082  // definition. If the declaration is not a definition, the
7083  // specialization may be defined later in the name- space in which
7084  // the explicit specialization was declared, or in a namespace
7085  // that encloses the one in which the explicit specialization was
7086  // declared.
7088  S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7089  << Specialized;
7090  return true;
7091  }
7092 
7093  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
7094  if (S.getLangOpts().MicrosoftExt) {
7095  // Do not warn for class scope explicit specialization during
7096  // instantiation, warning was already emitted during pattern
7097  // semantic analysis.
7098  if (!S.inTemplateInstantiation())
7099  S.Diag(Loc, diag::ext_function_specialization_in_class)
7100  << Specialized;
7101  } else {
7102  S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7103  << Specialized;
7104  return true;
7105  }
7106  }
7107 
7108  if (S.CurContext->isRecord() &&
7109  !S.CurContext->Equals(Specialized->getDeclContext())) {
7110  // Make sure that we're specializing in the right record context.
7111  // Otherwise, things can go horribly wrong.
7112  S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7113  << Specialized;
7114  return true;
7115  }
7116 
7117  // C++ [temp.class.spec]p6:
7118  // A class template partial specialization may be declared or redeclared
7119  // in any namespace scope in which its definition may be defined (14.5.1
7120  // and 14.5.2).
7121  DeclContext *SpecializedContext
7122  = Specialized->getDeclContext()->getEnclosingNamespaceContext();
7124 
7125  // Make sure that this redeclaration (or definition) occurs in an enclosing
7126  // namespace.
7127  // Note that HandleDeclarator() performs this check for explicit
7128  // specializations of function templates, static data members, and member
7129  // functions, so we skip the check here for those kinds of entities.
7130  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
7131  // Should we refactor that check, so that it occurs later?
7132  if (!DC->Encloses(SpecializedContext) &&
7133  !(isa<FunctionTemplateDecl>(Specialized) ||
7134  isa<FunctionDecl>(Specialized) ||
7135  isa<VarTemplateDecl>(Specialized) ||
7136  isa<VarDecl>(Specialized))) {
7137  if (isa<TranslationUnitDecl>(SpecializedContext))
7138  S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7139  << EntityKind << Specialized;
7140  else if (isa<NamespaceDecl>(SpecializedContext)) {
7141  int Diag = diag::err_template_spec_redecl_out_of_scope;
7142  if (S.getLangOpts().MicrosoftExt)
7143  Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7144  S.Diag(Loc, Diag) << EntityKind << Specialized
7145  << cast<NamedDecl>(SpecializedContext);
7146  } else
7147  llvm_unreachable("unexpected namespace context for specialization");
7148 
7149  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7150  } else if ((!PrevDecl ||
7152  getTemplateSpecializationKind(PrevDecl) ==
7154  // C++ [temp.exp.spec]p2:
7155  // An explicit specialization shall be declared in the namespace of which
7156  // the template is a member, or, for member templates, in the namespace
7157  // of which the enclosing class or enclosing class template is a member.
7158  // An explicit specialization of a member function, member class or
7159  // static data member of a class template shall be declared in the
7160  // namespace of which the class template is a member.
7161  //
7162  // C++11 [temp.expl.spec]p2:
7163  // An explicit specialization shall be declared in a namespace enclosing
7164  // the specialized template.
7165  // C++11 [temp.explicit]p3:
7166  // An explicit instantiation shall appear in an enclosing namespace of its
7167  // template.
7168  if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
7169  bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
7170  if (isa<TranslationUnitDecl>(SpecializedContext)) {
7171  assert(!IsCPlusPlus11Extension &&
7172  "DC encloses TU but isn't in enclosing namespace set");
7173  S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
7174  << EntityKind << Specialized;
7175  } else if (isa<NamespaceDecl>(SpecializedContext)) {
7176  int Diag;
7177  if (!IsCPlusPlus11Extension)
7178  Diag = diag::err_template_spec_decl_out_of_scope;
7179  else if (!S.getLangOpts().CPlusPlus11)
7180  Diag = diag::ext_template_spec_decl_out_of_scope;
7181  else
7182  Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
7183  S.Diag(Loc, Diag)
7184  << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
7185  }
7186 
7187  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7188  }
7189  }
7190 
7191  return false;
7192 }
7193 
7195  if (!E->isTypeDependent())
7196  return SourceLocation();
7197  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7198  Checker.TraverseStmt(E);
7199  if (Checker.MatchLoc.isInvalid())
7200  return E->getSourceRange();
7201  return Checker.MatchLoc;
7202 }
7203 
7205  if (!TL.getType()->isDependentType())
7206  return SourceLocation();
7207  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7208  Checker.TraverseTypeLoc(TL);
7209  if (Checker.MatchLoc.isInvalid())
7210  return TL.getSourceRange();
7211  return Checker.MatchLoc;
7212 }
7213 
7214 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7215 /// that checks non-type template partial specialization arguments.
7217  Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7218  const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7219  for (unsigned I = 0; I != NumArgs; ++I) {
7220  if (Args[I].getKind() == TemplateArgument::Pack) {
7222  S, TemplateNameLoc, Param, Args[I].pack_begin(),
7223  Args[I].pack_size(), IsDefaultArgument))
7224  return true;
7225 
7226  continue;
7227  }
7228 
7229  if (Args[I].getKind() != TemplateArgument::Expression)
7230  continue;
7231 
7232  Expr *ArgExpr = Args[I].getAsExpr();
7233 
7234  // We can have a pack expansion of any of the bullets below.
7235  if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7236  ArgExpr = Expansion->getPattern();
7237 
7238  // Strip off any implicit casts we added as part of type checking.
7239  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7240  ArgExpr = ICE->getSubExpr();
7241 
7242  // C++ [temp.class.spec]p8:
7243  // A non-type argument is non-specialized if it is the name of a
7244  // non-type parameter. All other non-type arguments are
7245  // specialized.
7246  //
7247  // Below, we check the two conditions that only apply to
7248  // specialized non-type arguments, so skip any non-specialized
7249  // arguments.
7250  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7251  if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7252  continue;
7253 
7254  // C++ [temp.class.spec]p9:
7255  // Within the argument list of a class template partial
7256  // specialization, the following restrictions apply:
7257  // -- A partially specialized non-type argument expression
7258  // shall not involve a template parameter of the partial
7259  // specialization except when the argument expression is a
7260  // simple identifier.
7261  // -- The type of a template parameter corresponding to a
7262  // specialized non-type argument shall not be dependent on a
7263  // parameter of the specialization.
7264  // DR1315 removes the first bullet, leaving an incoherent set of rules.
7265  // We implement a compromise between the original rules and DR1315:
7266  // -- A specialized non-type template argument shall not be
7267  // type-dependent and the corresponding template parameter
7268  // shall have a non-dependent type.
7269  SourceRange ParamUseRange =
7270  findTemplateParameterInType(Param->getDepth(), ArgExpr);
7271  if (ParamUseRange.isValid()) {
7272  if (IsDefaultArgument) {
7273  S.Diag(TemplateNameLoc,
7274  diag::err_dependent_non_type_arg_in_partial_spec);
7275  S.Diag(ParamUseRange.getBegin(),
7276  diag::note_dependent_non_type_default_arg_in_partial_spec)
7277  << ParamUseRange;
7278  } else {
7279  S.Diag(ParamUseRange.getBegin(),
7280  diag::err_dependent_non_type_arg_in_partial_spec)
7281  << ParamUseRange;
7282  }
7283  return true;
7284  }
7285 
7286  ParamUseRange = findTemplateParameter(
7287  Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7288  if (ParamUseRange.isValid()) {
7289  S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7290  diag::err_dependent_typed_non_type_arg_in_partial_spec)
7291  << Param->getType();
7292  S.Diag(Param->getLocation(), diag::note_template_param_here)
7293  << (IsDefaultArgument ? ParamUseRange : SourceRange())
7294  << ParamUseRange;
7295  return true;
7296  }
7297  }
7298 
7299  return false;
7300 }
7301 
7302 /// \brief Check the non-type template arguments of a class template
7303 /// partial specialization according to C++ [temp.class.spec]p9.
7304 ///
7305 /// \param TemplateNameLoc the location of the template name.
7306 /// \param PrimaryTemplate the template parameters of the primary class
7307 /// template.
7308 /// \param NumExplicit the number of explicitly-specified template arguments.
7309 /// \param TemplateArgs the template arguments of the class template
7310 /// partial specialization.
7311 ///
7312 /// \returns \c true if there was an error, \c false otherwise.
7314  SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7315  unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7316  // We have to be conservative when checking a template in a dependent
7317  // context.
7318  if (PrimaryTemplate->getDeclContext()->isDependentContext())
7319  return false;
7320 
7321  TemplateParameterList *TemplateParams =
7322  PrimaryTemplate->getTemplateParameters();
7323  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7325  = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7326  if (!Param)
7327  continue;
7328 
7329  if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7330  Param, &TemplateArgs[I],
7331  1, I >= NumExplicit))
7332  return true;
7333  }
7334 
7335  return false;
7336 }
7337 
7338 DeclResult
7340  TagUseKind TUK,
7341  SourceLocation KWLoc,
7342  SourceLocation ModulePrivateLoc,
7343  TemplateIdAnnotation &TemplateId,
7346  TemplateParameterLists,
7347  SkipBodyInfo *SkipBody) {
7348  assert(TUK != TUK_Reference && "References are not specializations");
7349 
7350  CXXScopeSpec &SS = TemplateId.SS;
7351 
7352  // NOTE: KWLoc is the location of the tag keyword. This will instead
7353  // store the location of the outermost template keyword in the declaration.
7354  SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7355  ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7356  SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7357  SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7358  SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7359 
7360  // Find the class template we're specializing
7361  TemplateName Name = TemplateId.Template.get();
7362  ClassTemplateDecl *ClassTemplate
7363  = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7364 
7365  if (!ClassTemplate) {
7366  Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7367  << (Name.getAsTemplateDecl() &&
7368  isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7369  return true;
7370  }
7371 
7372  bool isMemberSpecialization = false;
7373  bool isPartialSpecialization = false;
7374 
7375  // Check the validity of the template headers that introduce this
7376  // template.
7377  // FIXME: We probably shouldn't complain about these headers for
7378  // friend declarations.
7379  bool Invalid = false;
7380  TemplateParameterList *TemplateParams =
7381  MatchTemplateParametersToScopeSpecifier(
7382  KWLoc, TemplateNameLoc, SS, &TemplateId,
7383  TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7384  Invalid);
7385  if (Invalid)
7386  return true;
7387 
7388  if (TemplateParams && TemplateParams->size() > 0) {
7389  isPartialSpecialization = true;
7390 
7391  if (TUK == TUK_Friend) {
7392  Diag(KWLoc, diag::err_partial_specialization_friend)
7393  << SourceRange(LAngleLoc, RAngleLoc);
7394  return true;
7395  }
7396 
7397  // C++ [temp.class.spec]p10:
7398  // The template parameter list of a specialization shall not
7399  // contain default template argument values.
7400  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7401  Decl *Param = TemplateParams->getParam(I);
7402  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7403  if (TTP->hasDefaultArgument()) {
7404  Diag(TTP->getDefaultArgumentLoc(),
7405  diag::err_default_arg_in_partial_spec);
7406  TTP->removeDefaultArgument();
7407  }
7408  } else if (NonTypeTemplateParmDecl *NTTP
7409  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7410  if (Expr *DefArg = NTTP->getDefaultArgument()) {
7411  Diag(NTTP->getDefaultArgumentLoc(),
7412  diag::err_default_arg_in_partial_spec)
7413  << DefArg->getSourceRange();
7414  NTTP->removeDefaultArgument();
7415  }
7416  } else {
7417  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7418  if (TTP->hasDefaultArgument()) {
7420  diag::err_default_arg_in_partial_spec)
7421  << TTP->getDefaultArgument().getSourceRange();
7422  TTP->removeDefaultArgument();
7423  }
7424  }
7425  }
7426  } else if (TemplateParams) {
7427  if (TUK == TUK_Friend)
7428  Diag(KWLoc, diag::err_template_spec_friend)
7430  SourceRange(TemplateParams->getTemplateLoc(),
7431  TemplateParams->getRAngleLoc()))
7432  << SourceRange(LAngleLoc, RAngleLoc);
7433  } else {
7434  assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7435  }
7436 
7437  // Check that the specialization uses the same tag kind as the
7438  // original template.
7440  assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7441  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7442  Kind, TUK == TUK_Definition, KWLoc,
7443  ClassTemplate->getIdentifier())) {
7444  Diag(KWLoc, diag::err_use_with_wrong_tag)
7445  << ClassTemplate
7447  ClassTemplate->getTemplatedDecl()->getKindName());
7448  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7449  diag::note_previous_use);
7450  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7451  }
7452 
7453  // Translate the parser's template argument list in our AST format.
7454  TemplateArgumentListInfo TemplateArgs =
7455  makeTemplateArgumentListInfo(*this, TemplateId);
7456 
7457  // Check for unexpanded parameter packs in any of the template arguments.
7458  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7459  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7460  UPPC_PartialSpecialization))
7461  return true;
7462 
7463  // Check that the template argument list is well-formed for this
7464  // template.
7466  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7467  TemplateArgs, false, Converted))
7468  return true;
7469 
7470  // Find the class template (partial) specialization declaration that
7471  // corresponds to these arguments.
7472  if (isPartialSpecialization) {
7473  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7474  TemplateArgs.size(), Converted))
7475  return true;
7476 
7477  // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7478  // also do it during instantiation.
7479  bool InstantiationDependent;
7480  if (!Name.isDependent() &&
7482  TemplateArgs.arguments(), InstantiationDependent)) {
7483  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7484  << ClassTemplate->getDeclName();
7485  isPartialSpecialization = false;
7486  }
7487  }
7488 
7489  void *InsertPos = nullptr;
7490  ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7491 
7492  if (isPartialSpecialization)
7493  // FIXME: Template parameter list matters, too
7494  PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7495  else
7496  PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7497 
7498  ClassTemplateSpecializationDecl *Specialization = nullptr;
7499 
7500  // Check whether we can declare a class template specialization in
7501  // the current scope.
7502  if (TUK != TUK_Friend &&
7503  CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7504  TemplateNameLoc,
7505  isPartialSpecialization))
7506  return true;
7507 
7508  // The canonical type
7509  QualType CanonType;
7510  if (isPartialSpecialization) {
7511  // Build the canonical type that describes the converted template
7512  // arguments of the class template partial specialization.
7513  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7514  CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7515  Converted);
7516 
7517  if (Context.hasSameType(CanonType,
7518  ClassTemplate->getInjectedClassNameSpecialization())) {
7519  // C++ [temp.class.spec]p9b3:
7520  //
7521  // -- The argument list of the specialization shall not be identical
7522  // to the implicit argument list of the primary template.
7523  //
7524  // This rule has since been removed, because it's redundant given DR1495,
7525  // but we keep it because it produces better diagnostics and recovery.
7526  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7527  << /*class template*/0 << (TUK == TUK_Definition)
7528  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7529  return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7530  ClassTemplate->getIdentifier(),
7531  TemplateNameLoc,
7532  Attr,
7533  TemplateParams,
7534  AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7535  /*FriendLoc*/SourceLocation(),
7536  TemplateParameterLists.size() - 1,
7537  TemplateParameterLists.data());
7538  }
7539 
7540  // Create a new class template partial specialization declaration node.
7542  = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7545  ClassTemplate->getDeclContext(),
7546  KWLoc, TemplateNameLoc,
7547  TemplateParams,
7548  ClassTemplate,
7549  Converted,
7550  TemplateArgs,
7551  CanonType,
7552  PrevPartial);
7553  SetNestedNameSpecifier(Partial, SS);
7554  if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7555  Partial->setTemplateParameterListsInfo(
7556  Context, TemplateParameterLists.drop_back(1));
7557  }
7558 
7559  if (!PrevPartial)
7560  ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7561  Specialization = Partial;
7562 
7563  // If we are providing an explicit specialization of a member class
7564  // template specialization, make a note of that.
7565  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7566  PrevPartial->setMemberSpecialization();
7567 
7568  CheckTemplatePartialSpecialization(Partial);
7569  } else {
7570  // Create a new class template specialization declaration node for
7571  // this explicit specialization or friend declaration.
7572  Specialization
7574  ClassTemplate->getDeclContext(),
7575  KWLoc, TemplateNameLoc,
7576  ClassTemplate,
7577  Converted,
7578  PrevDecl);
7579  SetNestedNameSpecifier(Specialization, SS);
7580  if (TemplateParameterLists.size() > 0) {
7581  Specialization->setTemplateParameterListsInfo(Context,
7582  TemplateParameterLists);
7583  }
7584 
7585  if (!PrevDecl)
7586  ClassTemplate->AddSpecialization(Specialization, InsertPos);
7587 
7588  if (CurContext->isDependentContext()) {
7589  // -fms-extensions permits specialization of nested classes without
7590  // fully specializing the outer class(es).
7591  assert(getLangOpts().MicrosoftExt &&
7592  "Only possible with -fms-extensions!");
7593  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7594  CanonType = Context.getTemplateSpecializationType(
7595  CanonTemplate, Converted);
7596  } else {
7597  CanonType = Context.getTypeDeclType(Specialization);
7598  }
7599  }
7600 
7601  // C++ [temp.expl.spec]p6:
7602  // If a template, a member template or the member of a class template is
7603  // explicitly specialized then that specialization shall be declared
7604  // before the first use of that specialization that would cause an implicit
7605  // instantiation to take place, in every translation unit in which such a
7606  // use occurs; no diagnostic is required.
7607  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7608  bool Okay = false;
7609  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7610  // Is there any previous explicit specialization declaration?
7612  Okay = true;
7613  break;
7614  }
7615  }
7616 
7617  if (!Okay) {
7618  SourceRange Range(TemplateNameLoc, RAngleLoc);
7619  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7620  << Context.getTypeDeclType(Specialization) << Range;
7621 
7622  Diag(PrevDecl->getPointOfInstantiation(),
7623  diag::note_instantiation_required_here)
7624  << (PrevDecl->getTemplateSpecializationKind()
7626  return true;
7627  }
7628  }
7629 
7630  // If this is not a friend, note that this is an explicit specialization.
7631  if (TUK != TUK_Friend)
7633 
7634  // Check that this isn't a redefinition of this specialization.
7635  if (TUK == TUK_Definition) {
7636  RecordDecl *Def = Specialization->getDefinition();
7637  NamedDecl *Hidden = nullptr;
7638  if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7639  SkipBody->ShouldSkip = true;
7640  makeMergedDefinitionVisible(Hidden);
7641  // From here on out, treat this as just a redeclaration.
7642  TUK = TUK_Declaration;
7643  } else if (Def) {
7644  SourceRange Range(TemplateNameLoc, RAngleLoc);
7645  Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7646  Diag(Def->getLocation(), diag::note_previous_definition);
7647  Specialization->setInvalidDecl();
7648  return true;
7649  }
7650  }
7651 
7652  if (Attr)
7653  ProcessDeclAttributeList(S, Specialization, Attr);
7654 
7655  // Add alignment attributes if necessary; these attributes are checked when
7656  // the ASTContext lays out the structure.
7657  if (TUK == TUK_Definition) {
7658  AddAlignmentAttributesForRecord(Specialization);
7659  AddMsStructLayoutForRecord(Specialization);
7660  }
7661 
7662  if (ModulePrivateLoc.isValid())
7663  Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7664  << (isPartialSpecialization? 1 : 0)
7665  << FixItHint::CreateRemoval(ModulePrivateLoc);
7666 
7667  // Build the fully-sugared type for this class template
7668  // specialization as the user wrote in the specialization
7669  // itself. This means that we'll pretty-print the type retrieved
7670  // from the specialization's declaration the way that the user
7671  // actually wrote the specialization, rather than formatting the
7672  // name based on the "canonical" representation used to store the
7673  // template arguments in the specialization.
7674  TypeSourceInfo *WrittenTy
7675  = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7676  TemplateArgs, CanonType);
7677  if (TUK != TUK_Friend) {
7678  Specialization->setTypeAsWritten(WrittenTy);
7679  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7680  }
7681 
7682  // C++ [temp.expl.spec]p9:
7683  // A template explicit specialization is in the scope of the
7684  // namespace in which the template was defined.
7685  //
7686  // We actually implement this paragraph where we set the semantic
7687  // context (in the creation of the ClassTemplateSpecializationDecl),
7688  // but we also maintain the lexical context where the actual
7689  // definition occurs.
7690  Specialization->setLexicalDeclContext(CurContext);
7691 
7692  // We may be starting the definition of this specialization.
7693  if (TUK == TUK_Definition)
7694  Specialization->startDefinition();
7695 
7696  if (TUK == TUK_Friend) {
7697  FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7698  TemplateNameLoc,
7699  WrittenTy,
7700  /*FIXME:*/KWLoc);
7701  Friend->setAccess(AS_public);
7702  CurContext->addDecl(Friend);
7703  } else {
7704  // Add the specialization into its lexical context, so that it can
7705  // be seen when iterating through the list of declarations in that
7706  // context. However, specializations are not found by name lookup.
7707  CurContext->addDecl(Specialization);
7708  }
7709  return Specialization;
7710 }
7711 
7713  MultiTemplateParamsArg TemplateParameterLists,
7714  Declarator &D) {
7715  Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7716  ActOnDocumentableDecl(NewDecl);
7717  return NewDecl;
7718 }
7719 
7720 /// \brief Strips various properties off an implicit instantiation
7721 /// that has just been explicitly specialized.
7723  D->dropAttr<DLLImportAttr>();
7724  D->dropAttr<DLLExportAttr>();
7725 
7726  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7727  FD->setInlineSpecified(false);
7728 }
7729 
7730 /// \brief Compute the diagnostic location for an explicit instantiation
7731 // declaration or definition.
7733  NamedDecl* D, SourceLocation PointOfInstantiation) {
7734  // Explicit instantiations following a specialization have no effect and
7735  // hence no PointOfInstantiation. In that case, walk decl backwards
7736  // until a valid name loc is found.
7737  SourceLocation PrevDiagLoc = PointOfInstantiation;
7738  for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7739  Prev = Prev->getPreviousDecl()) {
7740  PrevDiagLoc = Prev->getLocation();
7741  }
7742  assert(PrevDiagLoc.isValid() &&
7743  "Explicit instantiation without point of instantiation?");
7744  return PrevDiagLoc;
7745 }
7746 
7747 /// \brief Diagnose cases where we have an explicit template specialization
7748 /// before/after an explicit template instantiation, producing diagnostics
7749 /// for those cases where they are required and determining whether the
7750 /// new specialization/instantiation will have any effect.
7751 ///
7752 /// \param NewLoc the location of the new explicit specialization or
7753 /// instantiation.
7754 ///
7755 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7756 ///
7757 /// \param PrevDecl the previous declaration of the entity.
7758 ///
7759 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7760 ///
7761 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7762 /// declaration was instantiated (either implicitly or explicitly).
7763 ///
7764 /// \param HasNoEffect will be set to true to indicate that the new
7765 /// specialization or instantiation has no effect and should be ignored.
7766 ///
7767 /// \returns true if there was an error that should prevent the introduction of
7768 /// the new declaration into the AST, false otherwise.
7769 bool
7772  NamedDecl *PrevDecl,
7774  SourceLocation PrevPointOfInstantiation,
7775  bool &HasNoEffect) {
7776  HasNoEffect = false;
7777 
7778  switch (NewTSK) {
7779  case TSK_Undeclared:
7781  assert(
7782  (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7783  "previous declaration must be implicit!");
7784  return false;
7785 
7787  switch (PrevTSK) {
7788  case TSK_Undeclared:
7790  // Okay, we're just specializing something that is either already
7791  // explicitly specialized or has merely been mentioned without any
7792  // instantiation.
7793  return false;
7794 
7796  if (PrevPointOfInstantiation.isInvalid()) {
7797  // The declaration itself has not actually been instantiated, so it is
7798  // still okay to specialize it.
7799  StripImplicitInstantiation(PrevDecl);
7800  return false;
7801  }
7802  // Fall through
7803  LLVM_FALLTHROUGH;
7804 
7807  assert((PrevTSK == TSK_ImplicitInstantiation ||
7808  PrevPointOfInstantiation.isValid()) &&
7809  "Explicit instantiation without point of instantiation?");
7810 
7811  // C++ [temp.expl.spec]p6:
7812  // If a template, a member template or the member of a class template
7813  // is explicitly specialized then that specialization shall be declared
7814  // before the first use of that specialization that would cause an
7815  // implicit instantiation to take place, in every translation unit in
7816  // which such a use occurs; no diagnostic is required.
7817  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7818  // Is there any previous explicit specialization declaration?
7820  return false;
7821  }
7822 
7823  Diag(NewLoc, diag::err_specialization_after_instantiation)
7824  << PrevDecl;
7825  Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7826  << (PrevTSK != TSK_ImplicitInstantiation);
7827 
7828  return true;
7829  }
7830  llvm_unreachable("The switch over PrevTSK must be exhaustive.");
7831 
7833  switch (PrevTSK) {
7835  // This explicit instantiation declaration is redundant (that's okay).
7836  HasNoEffect = true;
7837  return false;
7838 
7839  case TSK_Undeclared:
7841  // We're explicitly instantiating something that may have already been
7842  // implicitly instantiated; that's fine.
7843  return false;
7844 
7846  // C++0x [temp.explicit]p4:
7847  // For a given set of template parameters, if an explicit instantiation
7848  // of a template appears after a declaration of an explicit
7849  // specialization for that template, the explicit instantiation has no
7850  // effect.
7851  HasNoEffect = true;
7852  return false;
7853 
7855  // C++0x [temp.explicit]p10:
7856  // If an entity is the subject of both an explicit instantiation
7857  // declaration and an explicit instantiation definition in the same
7858  // translation unit, the definition shall follow the declaration.
7859  Diag(NewLoc,
7860  diag::err_explicit_instantiation_declaration_after_definition);
7861 
7862  // Explicit instantiations following a specialization have no effect and
7863  // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7864  // until a valid name loc is found.
7865  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7866  diag::note_explicit_instantiation_definition_here);
7867  HasNoEffect = true;
7868  return false;
7869  }
7870 
7872  switch (PrevTSK) {
7873  case TSK_Undeclared:
7875  // We're explicitly instantiating something that may have already been
7876  // implicitly instantiated; that's fine.
7877  return false;
7878 
7880  // C++ DR 259, C++0x [temp.explicit]p4:
7881  // For a given set of template parameters, if an explicit
7882  // instantiation of a template appears after a declaration of
7883  // an explicit specialization for that template, the explicit
7884  // instantiation has no effect.
7885  Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7886  << PrevDecl;
7887  Diag(PrevDecl->getLocation(),
7888  diag::note_previous_template_specialization);
7889  HasNoEffect = true;
7890  return false;
7891 
7893  // We're explicity instantiating a definition for something for which we
7894  // were previously asked to suppress instantiations. That's fine.
7895 
7896  // C++0x [temp.explicit]p4:
7897  // For a given set of template parameters, if an explicit instantiation
7898  // of a template appears after a declaration of an explicit
7899  // specialization for that template, the explicit instantiation has no
7900  // effect.
7901  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7902  // Is there any previous explicit specialization declaration?
7904  HasNoEffect = true;
7905  break;
7906  }
7907  }
7908 
7909  return false;
7910 
7912  // C++0x [temp.spec]p5:
7913  // For a given template and a given set of template-arguments,
7914  // - an explicit instantiation definition shall appear at most once
7915  // in a program,
7916 
7917  // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7918  Diag(NewLoc, (getLangOpts().MSVCCompat)
7919  ? diag::ext_explicit_instantiation_duplicate
7920  : diag::err_explicit_instantiation_duplicate)
7921  << PrevDecl;
7922  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7923  diag::note_previous_explicit_instantiation);
7924  HasNoEffect = true;
7925  return false;
7926  }
7927  }
7928 
7929  llvm_unreachable("Missing specialization/instantiation case?");
7930 }
7931 
7932 /// \brief Perform semantic analysis for the given dependent function
7933 /// template specialization.
7934 ///
7935 /// The only possible way to get a dependent function template specialization
7936 /// is with a friend declaration, like so:
7937 ///
7938 /// \code
7939 /// template <class T> void foo(T);
7940 /// template <class T> class A {
7941 /// friend void foo<>(T);
7942 /// };
7943 /// \endcode
7944 ///
7945 /// There really isn't any useful analysis we can do here, so we
7946 /// just store the information.
7947 bool
7949  const TemplateArgumentListInfo &ExplicitTemplateArgs,
7951  // Remove anything from Previous that isn't a function template in
7952  // the correct context.
7953  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7954  LookupResult::Filter F = Previous.makeFilter();
7955  while (F.hasNext()) {
7956  NamedDecl *D = F.next()->getUnderlyingDecl();
7957  if (!isa<FunctionTemplateDecl>(D) ||
7958  !FDLookupContext->InEnclosingNamespaceSetOf(
7960  F.erase();
7961  }
7962  F.done();
7963 
7964  // Should this be diagnosed here?
7965  if (Previous.empty()) return true;
7966 
7967  FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7968  ExplicitTemplateArgs);
7969  return false;
7970 }
7971 
7972 /// \brief Perform semantic analysis for the given function template
7973 /// specialization.
7974 ///
7975 /// This routine performs all of the semantic analysis required for an
7976 /// explicit function template specialization. On successful completion,
7977 /// the function declaration \p FD will become a function template
7978 /// specialization.
7979 ///
7980 /// \param FD the function declaration, which will be updated to become a
7981 /// function template specialization.
7982 ///
7983 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7984 /// if any. Note that this may be valid info even when 0 arguments are
7985 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7986 /// as it anyway contains info on the angle brackets locations.
7987 ///
7988 /// \param Previous the set of declarations that may be specialized by
7989 /// this function specialization.
7991  FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7993  // The set of function template specializations that could match this
7994  // explicit function template specialization.
7995  UnresolvedSet<8> Candidates;
7996  TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7997  /*ForTakingAddress=*/false);
7998 
7999  llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8000  ConvertedTemplateArgs;
8001 
8002  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8003  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8004  I != E; ++I) {
8005  NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8006  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8007  // Only consider templates found within the same semantic lookup scope as
8008  // FD.
8009  if (!FDLookupContext->InEnclosingNamespaceSetOf(
8010  Ovl->getDeclContext()->getRedeclContext()))
8011  continue;
8012 
8013  // When matching a constexpr member function template specialization
8014  // against the primary template, we don't yet know whether the
8015  // specialization has an implicit 'const' (because we don't know whether
8016  // it will be a static member function until we know which template it
8017  // specializes), so adjust it now assuming it specializes this template.
8018  QualType FT = FD->getType();
8019  if (FD->isConstexpr()) {
8020  CXXMethodDecl *OldMD =
8021  dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8022  if (OldMD && OldMD->isConst()) {
8023  const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8026  FT = Context.getFunctionType(FPT->getReturnType(),
8027  FPT->getParamTypes(), EPI);
8028  }
8029  }
8030 
8032  if (ExplicitTemplateArgs)
8033  Args = *ExplicitTemplateArgs;
8034 
8035  // C++ [temp.expl.spec]p11:
8036  // A trailing template-argument can be left unspecified in the
8037  // template-id naming an explicit function template specialization
8038  // provided it can be deduced from the function argument type.
8039  // Perform template argument deduction to determine whether we may be
8040  // specializing this template.
8041  // FIXME: It is somewhat wasteful to build
8042  TemplateDeductionInfo Info(FailedCandidates.getLocation());
8043  FunctionDecl *Specialization = nullptr;
8045  cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8046  ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8047  Info)) {
8048  // Template argument deduction failed; record why it failed, so
8049  // that we can provide nifty diagnostics.
8050  FailedCandidates.addCandidate().set(
8051  I.getPair(), FunTmpl->getTemplatedDecl(),
8052  MakeDeductionFailureInfo(Context, TDK, Info));
8053  (void)TDK;
8054  continue;
8055  }
8056 
8057  // Target attributes are part of the cuda function signature, so
8058  // the deduced template's cuda target must match that of the
8059  // specialization. Given that C++ template deduction does not
8060  // take target attributes into account, we reject candidates
8061  // here that have a different target.
8062  if (LangOpts.CUDA &&
8063  IdentifyCUDATarget(Specialization,
8064  /* IgnoreImplicitHDAttributes = */ true) !=
8065  IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
8066  FailedCandidates.addCandidate().set(
8067  I.getPair(), FunTmpl->getTemplatedDecl(),
8068  MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8069  continue;
8070  }
8071 
8072  // Record this candidate.
8073  if (ExplicitTemplateArgs)
8074  ConvertedTemplateArgs[Specialization] = std::move(Args);
8075  Candidates.addDecl(Specialization, I.getAccess());
8076  }
8077  }
8078 
8079  // Find the most specialized function template.
8080  UnresolvedSetIterator Result = getMostSpecialized(
8081  Candidates.begin(), Candidates.end(), FailedCandidates,
8082  FD->getLocation(),
8083  PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8084  PDiag(diag::err_function_template_spec_ambiguous)
8085  << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8086  PDiag(diag::note_function_template_spec_matched));
8087 
8088  if (Result == Candidates.end())
8089  return true;
8090 
8091  // Ignore access information; it doesn't figure into redeclaration checking.
8092  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8093 
8095  = Specialization->getTemplateSpecializationInfo();
8096  assert(SpecInfo && "Function template specialization info missing?");
8097 
8098  // Note: do not overwrite location info if previous template
8099  // specialization kind was explicit.
8101  if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8102  Specialization->setLocation(FD->getLocation());
8103  Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8104  // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8105  // function can differ from the template declaration with respect to
8106  // the constexpr specifier.
8107  // FIXME: We need an update record for this AST mutation.
8108  // FIXME: What if there are multiple such prior declarations (for instance,
8109  // from different modules)?
8110  Specialization->setConstexpr(FD->isConstexpr());
8111  }
8112 
8113  // FIXME: Check if the prior specialization has a point of instantiation.
8114  // If so, we have run afoul of .
8115 
8116  // If this is a friend declaration, then we're not really declaring
8117  // an explicit specialization.
8118  bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8119 
8120  // Check the scope of this explicit specialization.
8121  if (!isFriend &&
8123  Specialization->getPrimaryTemplate(),
8124  Specialization, FD->getLocation(),
8125  false))
8126  return true;
8127 
8128  // C++ [temp.expl.spec]p6:
8129  // If a template, a member template or the member of a class template is
8130  // explicitly specialized then that specialization shall be declared
8131  // before the first use of that specialization that would cause an implicit
8132  // instantiation to take place, in every translation unit in which such a
8133  // use occurs; no diagnostic is required.
8134  bool HasNoEffect = false;
8135  if (!isFriend &&
8136  CheckSpecializationInstantiationRedecl(FD->getLocation(),
8138  Specialization,
8139  SpecInfo->getTemplateSpecializationKind(),
8140  SpecInfo->getPointOfInstantiation(),
8141  HasNoEffect))
8142  return true;
8143 
8144  // Mark the prior declaration as an explicit specialization, so that later
8145  // clients know that this is an explicit specialization.
8146  if (!isFriend) {
8147  // Since explicit specializations do not inherit '=delete' from their
8148  // primary function template - check if the 'specialization' that was
8149  // implicitly generated (during template argument deduction for partial
8150  // ordering) from the most specialized of all the function templates that
8151  // 'FD' could have been specializing, has a 'deleted' definition. If so,
8152  // first check that it was implicitly generated during template argument
8153  // deduction by making sure it wasn't referenced, and then reset the deleted
8154  // flag to not-deleted, so that we can inherit that information from 'FD'.
8155  if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8156  !Specialization->getCanonicalDecl()->isReferenced()) {
8157  // FIXME: This assert will not hold in the presence of modules.
8158  assert(
8159  Specialization->getCanonicalDecl() == Specialization &&
8160  "This must be the only existing declaration of this specialization");
8161  // FIXME: We need an update record for this AST mutation.
8162  Specialization->setDeletedAsWritten(false);
8163  }
8164  // FIXME: We need an update record for this AST mutation.
8166  MarkUnusedFileScopedDecl(Specialization);
8167  }
8168 
8169  // Turn the given function declaration into a function template
8170  // specialization, with the template arguments from the previous
8171  // specialization.
8172  // Take copies of (semantic and syntactic) template argument lists.
8173  const TemplateArgumentList* TemplArgs = new (Context)
8174  TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8175  FD->setFunctionTemplateSpecialization(
8176  Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8177  SpecInfo->getTemplateSpecializationKind(),
8178  ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8179 
8180  // A function template specialization inherits the target attributes
8181  // of its template. (We require the attributes explicitly in the
8182  // code to match, but a template may have implicit attributes by
8183  // virtue e.g. of being constexpr, and it passes these implicit
8184  // attributes on to its specializations.)
8185  if (LangOpts.CUDA)
8186  inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8187 
8188  // The "previous declaration" for this function template specialization is
8189  // the prior function template specialization.
8190  Previous.clear();
8191  Previous.addDecl(Specialization);
8192  return false;
8193 }
8194 
8195 /// \brief Perform semantic analysis for the given non-template member
8196 /// specialization.
8197 ///
8198 /// This routine performs all of the semantic analysis required for an
8199 /// explicit member function specialization. On successful completion,
8200 /// the function declaration \p FD will become a member function
8201 /// specialization.
8202 ///
8203 /// \param Member the member declaration, which will be updated to become a
8204 /// specialization.
8205 ///
8206 /// \param Previous the set of declarations, one of which may be specialized
8207 /// by this function specialization; the set will be modified to contain the
8208 /// redeclared member.
8209 bool
8211  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8212 
8213  // Try to find the member we are instantiating.
8214  NamedDecl *FoundInstantiation = nullptr;
8215  NamedDecl *Instantiation = nullptr;
8216  NamedDecl *InstantiatedFrom = nullptr;
8217  MemberSpecializationInfo *MSInfo = nullptr;
8218 
8219  if (Previous.empty()) {
8220  // Nowhere to look anyway.
8221  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8222  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8223  I != E; ++I) {
8224  NamedDecl *D = (*I)->getUnderlyingDecl();
8225  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8226  QualType Adjusted = Function->getType();
8227  if (!hasExplicitCallingConv(Adjusted))
8228  Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8229  if (Context.hasSameType(Adjusted, Method->getType())) {
8230  FoundInstantiation = *I;
8231  Instantiation = Method;
8232  InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8233  MSInfo = Method->getMemberSpecializationInfo();
8234  break;
8235  }
8236  }
8237  }
8238  } else if (isa<VarDecl>(Member)) {
8239  VarDecl *PrevVar;
8240  if (Previous.isSingleResult() &&
8241  (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8242  if (PrevVar->isStaticDataMember()) {
8243  FoundInstantiation = Previous.getRepresentativeDecl();
8244  Instantiation = PrevVar;
8245  InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8246  MSInfo = PrevVar->getMemberSpecializationInfo();
8247  }
8248  } else if (isa<RecordDecl>(Member)) {
8249  CXXRecordDecl *PrevRecord;
8250  if (Previous.isSingleResult() &&
8251  (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8252  FoundInstantiation = Previous.getRepresentativeDecl();
8253  Instantiation = PrevRecord;
8254  InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8255  MSInfo = PrevRecord->getMemberSpecializationInfo();
8256  }
8257  } else if (isa<EnumDecl>(Member)) {
8258  EnumDecl *PrevEnum;
8259  if (Previous.isSingleResult() &&
8260  (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8261  FoundInstantiation = Previous.getRepresentativeDecl();
8262  Instantiation = PrevEnum;
8263  InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8264  MSInfo = PrevEnum->getMemberSpecializationInfo();
8265  }
8266  }
8267 
8268  if (!Instantiation) {
8269  // There is no previous declaration that matches. Since member
8270  // specializations are always out-of-line, the caller will complain about
8271  // this mismatch later.
8272  return false;
8273  }
8274 
8275  // A member specialization in a friend declaration isn't really declaring
8276  // an explicit specialization, just identifying a specific (possibly implicit)
8277  // specialization. Don't change the template specialization kind.
8278  //
8279  // FIXME: Is this really valid? Other compilers reject.
8280  if (Member->getFriendObjectKind() != Decl::FOK_None) {
8281  // Preserve instantiation information.
8282  if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8283  cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8284  cast<CXXMethodDecl>(InstantiatedFrom),
8285  cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8286  } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8287  cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8288  cast<CXXRecordDecl>(InstantiatedFrom),
8289  cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8290  }
8291 
8292  Previous.clear();
8293  Previous.addDecl(FoundInstantiation);
8294  return false;
8295  }
8296 
8297  // Make sure that this is a specialization of a member.
8298  if (!InstantiatedFrom) {
8299  Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8300  << Member;
8301  Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8302  return true;
8303  }
8304 
8305  // C++ [temp.expl.spec]p6:
8306  // If a template, a member template or the member of a class template is
8307  // explicitly specialized then that specialization shall be declared
8308  // before the first use of that specialization that would cause an implicit
8309  // instantiation to take place, in every translation unit in which such a
8310  // use occurs; no diagnostic is required.
8311  assert(MSInfo && "Member specialization info missing?");
8312 
8313  bool HasNoEffect = false;
8314  if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8316  Instantiation,
8318  MSInfo->getPointOfInstantiation(),
8319  HasNoEffect))
8320  return true;
8321 
8322  // Check the scope of this explicit specialization.
8324  InstantiatedFrom,
8325  Instantiation, Member->getLocation(),
8326  false))
8327  return true;
8328 
8329  // Note that this member specialization is an "instantiation of" the
8330  // corresponding member of the original template.
8331  if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8332  FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8333  if (InstantiationFunction->getTemplateSpecializationKind() ==
8335  // Explicit specializations of member functions of class templates do not
8336  // inherit '=delete' from the member function they are specializing.
8337  if (InstantiationFunction->isDeleted()) {
8338  // FIXME: This assert will not hold in the presence of modules.
8339  assert(InstantiationFunction->getCanonicalDecl() ==
8340  InstantiationFunction);
8341  // FIXME: We need an update record for this AST mutation.
8342  InstantiationFunction->setDeletedAsWritten(false);
8343  }
8344  }
8345 
8346  MemberFunction->setInstantiationOfMemberFunction(
8347  cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8348  } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8349  MemberVar->setInstantiationOfStaticDataMember(
8350  cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8351  } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8352  MemberClass->setInstantiationOfMemberClass(
8353  cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8354  } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8355  MemberEnum->setInstantiationOfMemberEnum(
8356  cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8357  } else {
8358  llvm_unreachable("unknown member specialization kind");
8359  }
8360 
8361  // Save the caller the trouble of having to figure out which declaration
8362  // this specialization matches.
8363  Previous.clear();
8364  Previous.addDecl(FoundInstantiation);
8365  return false;
8366 }
8367 
8368 /// Complete the explicit specialization of a member of a class template by
8369 /// updating the instantiated member to be marked as an explicit specialization.
8370 ///
8371 /// \param OrigD The member declaration instantiated from the template.
8372 /// \param Loc The location of the explicit specialization of the member.
8373 template<typename DeclT>
8374 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8375  SourceLocation Loc) {
8376  if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8377  return;
8378 
8379  // FIXME: Inform AST mutation listeners of this AST mutation.
8380  // FIXME: If there are multiple in-class declarations of the member (from
8381  // multiple modules, or a declaration and later definition of a member type),
8382  // should we update all of them?
8383  OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8384  OrigD->setLocation(Loc);
8385 }
8386 
8389  NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8390  if (Instantiation == Member)
8391  return;
8392 
8393  if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8394  completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8395  else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8396  completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8397  else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8398  completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8399  else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8400  completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8401  else
8402  llvm_unreachable("unknown member specialization kind");
8403 }
8404 
8405 /// \brief Check the scope of an explicit instantiation.
8406 ///
8407 /// \returns true if a serious error occurs, false otherwise.
8409  SourceLocation InstLoc,
8410  bool WasQualifiedName) {
8412  DeclContext *CurContext = S.CurContext->getRedeclContext();
8413 
8414  if (CurContext->isRecord()) {
8415  S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8416  << D;
8417  return true;
8418  }
8419 
8420  // C++11 [temp.explicit]p3:
8421  // An explicit instantiation shall appear in an enclosing namespace of its
8422  // template. If the name declared in the explicit instantiation is an
8423  // unqualified name, the explicit instantiation shall appear in the
8424  // namespace where its template is declared or, if that namespace is inline
8425  // (7.3.1), any namespace from its enclosing namespace set.
8426  //
8427  // This is DR275, which we do not retroactively apply to C++98/03.
8428  if (WasQualifiedName) {
8429  if (CurContext->Encloses(OrigContext))
8430  return false;
8431  } else {
8432  if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8433  return false;
8434  }
8435 
8436  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8437  if (WasQualifiedName)
8438  S.Diag(InstLoc,
8439  S.getLangOpts().CPlusPlus11?
8440  diag::err_explicit_instantiation_out_of_scope :
8441  diag::warn_explicit_instantiation_out_of_scope_0x)
8442  << D << NS;
8443  else
8444  S.Diag(InstLoc,
8445  S.getLangOpts().CPlusPlus11?
8446  diag::err_explicit_instantiation_unqualified_wrong_namespace :
8447  diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8448  << D << NS;
8449  } else
8450  S.Diag(InstLoc,
8451  S.getLangOpts().CPlusPlus11?
8452  diag::err_explicit_instantiation_must_be_global :
8453  diag::warn_explicit_instantiation_must_be_global_0x)
8454  << D;
8455  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8456  return false;
8457 }
8458 
8459 /// \brief Determine whether the given scope specifier has a template-id in it.
8461  if (!SS.isSet())
8462  return false;
8463 
8464  // C++11 [temp.explicit]p3:
8465  // If the explicit instantiation is for a member function, a member class
8466  // or a static data member of a class template specialization, the name of
8467  // the class template specialization in the qualified-id for the member
8468  // name shall be a simple-template-id.
8469  //
8470  // C++98 has the same restriction, just worded differently.
8471  for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8472  NNS = NNS->getPrefix())
8473  if (const Type *T = NNS->getAsType())
8474  if (isa<TemplateSpecializationType>(T))
8475  return true;
8476 
8477  return false;
8478 }
8479 
8480 /// Make a dllexport or dllimport attr on a class template specialization take
8481 /// effect.
8484  auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8485  assert(A && "dllExportImportClassTemplateSpecialization called "
8486  "on Def without dllexport or dllimport");
8487 
8488  // We reject explicit instantiations in class scope, so there should
8489  // never be any delayed exported classes to worry about.
8490  assert(S.DelayedDllExportClasses.empty() &&
8491  "delayed exports present at explicit instantiation");
8493 
8494  // Propagate attribute to base class templates.
8495  for (auto &B : Def->bases()) {
8496  if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8497  B.getType()->getAsCXXRecordDecl()))
8499  }
8500 
8502 }
8503 
8504 // Explicit instantiation of a class template specialization
8505 DeclResult
8507  SourceLocation ExternLoc,
8508  SourceLocation TemplateLoc,
8509  unsigned TagSpec,
8510  SourceLocation KWLoc,
8511  const CXXScopeSpec &SS,
8512  TemplateTy TemplateD,
8513  SourceLocation TemplateNameLoc,
8514  SourceLocation LAngleLoc,
8515  ASTTemplateArgsPtr TemplateArgsIn,
8516  SourceLocation RAngleLoc,
8517  AttributeList *Attr) {
8518  // Find the class template we're specializing
8519  TemplateName Name = TemplateD.get();
8520  TemplateDecl *TD = Name.getAsTemplateDecl();
8521  // Check that the specialization uses the same tag kind as the
8522  // original template.
8524  assert(Kind != TTK_Enum &&
8525  "Invalid enum tag in class template explicit instantiation!");
8526 
8527  ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8528 
8529  if (!ClassTemplate) {
8530  NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8531  Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8532  Diag(TD->getLocation(), diag::note_previous_use);
8533  return true;
8534  }
8535 
8536  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8537  Kind, /*isDefinition*/false, KWLoc,
8538  ClassTemplate->getIdentifier())) {
8539  Diag(KWLoc, diag::err_use_with_wrong_tag)
8540  << ClassTemplate
8542  ClassTemplate->getTemplatedDecl()->getKindName());
8543  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8544  diag::note_previous_use);
8545  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8546  }
8547 
8548  // C++0x [temp.explicit]p2:
8549  // There are two forms of explicit instantiation: an explicit instantiation
8550  // definition and an explicit instantiation declaration. An explicit
8551  // instantiation declaration begins with the extern keyword. [...]
8552  TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8555 
8557  // Check for dllexport class template instantiation declarations.
8558  for (AttributeList *A = Attr; A; A = A->getNext()) {
8559  if (A->getKind() == AttributeList::AT_DLLExport) {
8560  Diag(ExternLoc,
8561  diag::warn_attribute_dllexport_explicit_instantiation_decl);
8562  Diag(A->getLoc(), diag::note_attribute);
8563  break;
8564  }
8565  }
8566 
8567  if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8568  Diag(ExternLoc,
8569  diag::warn_attribute_dllexport_explicit_instantiation_decl);
8570  Diag(A->getLocation(), diag::note_attribute);
8571  }
8572  }
8573 
8574  // In MSVC mode, dllimported explicit instantiation definitions are treated as
8575  // instantiation declarations for most purposes.
8576  bool DLLImportExplicitInstantiationDef = false;
8578  Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8579  // Check for dllimport class template instantiation definitions.
8580  bool DLLImport =
8581  ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8582  for (AttributeList *A = Attr; A; A = A->getNext()) {
8583  if (A->getKind() == AttributeList::AT_DLLImport)
8584  DLLImport = true;
8585  if (A->getKind() == AttributeList::AT_DLLExport) {
8586  // dllexport trumps dllimport here.
8587  DLLImport = false;
8588  break;
8589  }
8590  }
8591  if (DLLImport) {
8593  DLLImportExplicitInstantiationDef = true;
8594  }
8595  }
8596 
8597  // Translate the parser's template argument list in our AST format.
8598  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8599  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8600 
8601  // Check that the template argument list is well-formed for this
8602  // template.
8604  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8605  TemplateArgs, false, Converted))
8606  return true;
8607 
8608  // Find the class template specialization declaration that
8609  // corresponds to these arguments.
8610  void *InsertPos = nullptr;
8612  = ClassTemplate->findSpecialization(Converted, InsertPos);
8613 
8614  TemplateSpecializationKind PrevDecl_TSK
8615  = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8616 
8617  // C++0x [temp.explicit]p2:
8618  // [...] An explicit instantiation shall appear in an enclosing
8619  // namespace of its template. [...]
8620  //
8621  // This is C++ DR 275.
8622  if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8623  SS.isSet()))
8624  return true;
8625 
8626  ClassTemplateSpecializationDecl *Specialization = nullptr;
8627 
8628  bool HasNoEffect = false;
8629  if (PrevDecl) {
8630  if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8631  PrevDecl, PrevDecl_TSK,
8632  PrevDecl->getPointOfInstantiation(),
8633  HasNoEffect))
8634  return PrevDecl;
8635 
8636  // Even though HasNoEffect == true means that this explicit instantiation
8637  // has no effect on semantics, we go on to put its syntax in the AST.
8638 
8639  if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8640  PrevDecl_TSK == TSK_Undeclared) {
8641  // Since the only prior class template specialization with these
8642  // arguments was referenced but not declared, reuse that
8643  // declaration node as our own, updating the source location
8644  // for the template name to reflect our new declaration.
8645  // (Other source locations will be updated later.)
8646  Specialization = PrevDecl;
8647  Specialization->setLocation(TemplateNameLoc);
8648  PrevDecl = nullptr;
8649  }
8650 
8651  if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8652  DLLImportExplicitInstantiationDef) {
8653  // The new specialization might add a dllimport attribute.
8654  HasNoEffect = false;
8655  }
8656  }
8657 
8658  if (!Specialization) {
8659  // Create a new class template specialization declaration node for
8660  // this explicit specialization.
8661  Specialization
8663  ClassTemplate->getDeclContext(),
8664  KWLoc, TemplateNameLoc,
8665  ClassTemplate,
8666  Converted,
8667  PrevDecl);
8668  SetNestedNameSpecifier(Specialization, SS);
8669 
8670  if (!HasNoEffect && !PrevDecl) {
8671  // Insert the new specialization.
8672  ClassTemplate->AddSpecialization(Specialization, InsertPos);
8673  }
8674  }
8675 
8676  // Build the fully-sugared type for this explicit instantiation as
8677  // the user wrote in the explicit instantiation itself. This means
8678  // that we'll pretty-print the type retrieved from the
8679  // specialization's declaration the way that the user actually wrote
8680  // the explicit instantiation, rather than formatting the name based
8681  // on the "canonical" representation used to store the template
8682  // arguments in the specialization.
8683  TypeSourceInfo *WrittenTy
8684  = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8685  TemplateArgs,
8686  Context.getTypeDeclType(Specialization));
8687  Specialization->setTypeAsWritten(WrittenTy);
8688 
8689  // Set source locations for keywords.
8690  Specialization->setExternLoc(ExternLoc);
8691  Specialization->setTemplateKeywordLoc(TemplateLoc);
8692  Specialization->setBraceRange(SourceRange());
8693 
8694  bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8695  if (Attr)
8696  ProcessDeclAttributeList(S, Specialization, Attr);
8697 
8698  // Add the explicit instantiation into its lexical context. However,
8699  // since explicit instantiations are never found by name lookup, we
8700  // just put it into the declaration context directly.
8701  Specialization->setLexicalDeclContext(CurContext);
8702  CurContext->addDecl(Specialization);
8703 
8704  // Syntax is now OK, so return if it has no other effect on semantics.
8705  if (HasNoEffect) {
8706  // Set the template specialization kind.
8707  Specialization->setTemplateSpecializationKind(TSK);
8708  return Specialization;
8709  }
8710 
8711  // C++ [temp.explicit]p3:
8712  // A definition of a class template or class member template
8713  // shall be in scope at the point of the explicit instantiation of
8714  // the class template or class member template.
8715  //
8716  // This check comes when we actually try to perform the
8717  // instantiation.
8719  = cast_or_null<ClassTemplateSpecializationDecl>(
8720  Specialization->getDefinition());
8721  if (!Def)
8722  InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8723  else if (TSK == TSK_ExplicitInstantiationDefinition) {
8724  MarkVTableUsed(TemplateNameLoc, Specialization, true);
8725  Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8726  }
8727 
8728  // Instantiate the members of this class template specialization.
8729  Def = cast_or_null<ClassTemplateSpecializationDecl>(
8730  Specialization->getDefinition());
8731  if (Def) {
8733  // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8734  // TSK_ExplicitInstantiationDefinition
8735  if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8737  DLLImportExplicitInstantiationDef)) {
8738  // FIXME: Need to notify the ASTMutationListener that we did this.
8740 
8741  if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8742  (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8743  Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8744  // In the MS ABI, an explicit instantiation definition can add a dll
8745  // attribute to a template with a previous instantiation declaration.
8746  // MinGW doesn't allow this.
8747  auto *A = cast<InheritableAttr>(
8748  getDLLAttr(Specialization)->clone(getASTContext()));
8749  A->setInherited(true);
8750  Def->addAttr(A);
8752  }
8753  }
8754 
8755  // Fix a TSK_ImplicitInstantiation followed by a
8756  // TSK_ExplicitInstantiationDefinition
8757  bool NewlyDLLExported =
8758  !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8759  if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8760  (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8761  Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8762  // In the MS ABI, an explicit instantiation definition can add a dll
8763  // attribute to a template with a previous implicit instantiation.
8764  // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8765  // avoid potentially strange codegen behavior. For example, if we extend
8766  // this conditional to dllimport, and we have a source file calling a
8767  // method on an implicitly instantiated template class instance and then
8768  // declaring a dllimport explicit instantiation definition for the same
8769  // template class, the codegen for the method call will not respect the
8770  // dllimport, while it will with cl. The Def will already have the DLL
8771  // attribute, since the Def and Specialization will be the same in the
8772  // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8773  // attribute to the Specialization; we just need to make it take effect.
8774  assert(Def == Specialization &&
8775  "Def and Specialization should match for implicit instantiation");
8777  }
8778 
8779  // Set the template specialization kind. Make sure it is set before
8780  // instantiating the members which will trigger ASTConsumer callbacks.
8781  Specialization->setTemplateSpecializationKind(TSK);
8782  InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8783  } else {
8784 
8785  // Set the template specialization kind.
8786  Specialization->setTemplateSpecializationKind(TSK);
8787  }
8788 
8789  return Specialization;
8790 }
8791 
8792 // Explicit instantiation of a member class of a class template.
8793 DeclResult
8795  SourceLocation ExternLoc,
8796  SourceLocation TemplateLoc,
8797  unsigned TagSpec,
8798  SourceLocation KWLoc,
8799  CXXScopeSpec &SS,
8800  IdentifierInfo *Name,
8801  SourceLocation NameLoc,
8802  AttributeList *Attr) {
8803 
8804  bool Owned = false;
8805  bool IsDependent = false;
8806  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8807  KWLoc, SS, Name, NameLoc, Attr, AS_none,
8808  /*ModulePrivateLoc=*/SourceLocation(),
8809  MultiTemplateParamsArg(), Owned, IsDependent,
8810  SourceLocation(), false, TypeResult(),
8811  /*IsTypeSpecifier*/false,
8812  /*IsTemplateParamOrArg*/false);
8813  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8814 
8815  if (!TagD)
8816  return true;
8817 
8818  TagDecl *Tag = cast<TagDecl>(TagD);
8819  assert(!Tag->isEnum() && "shouldn't see enumerations here");
8820 
8821  if (Tag->isInvalidDecl())
8822  return true;
8823 
8824  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8825  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8826  if (!Pattern) {
8827  Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8828  << Context.getTypeDeclType(Record);
8829  Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8830  return true;
8831  }
8832 
8833  // C++0x [temp.explicit]p2:
8834  // If the explicit instantiation is for a class or member class, the
8835  // elaborated-type-specifier in the declaration shall include a
8836  // simple-template-id.
8837  //
8838  // C++98 has the same restriction, just worded differently.
8839  if (!ScopeSpecifierHasTemplateId(SS))
8840  Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8841  << Record << SS.getRange();
8842 
8843  // C++0x [temp.explicit]p2:
8844  // There are two forms of explicit instantiation: an explicit instantiation
8845  // definition and an explicit instantiation declaration. An explicit
8846  // instantiation declaration begins with the extern keyword. [...]
8850 
8851  // C++0x [temp.explicit]p2:
8852  // [...] An explicit instantiation shall appear in an enclosing
8853  // namespace of its template. [...]
8854  //
8855  // This is C++ DR 275.
8856  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8857 
8858  // Verify that it is okay to explicitly instantiate here.
8859  CXXRecordDecl *PrevDecl
8860  = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8861  if (!PrevDecl && Record->getDefinition())
8862  PrevDecl = Record;
8863  if (PrevDecl) {
8865  bool HasNoEffect = false;
8866  assert(MSInfo && "No member specialization information?");
8867  if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8868  PrevDecl,
8870  MSInfo->getPointOfInstantiation(),
8871  HasNoEffect))
8872  return true;
8873  if (HasNoEffect)
8874  return TagD;
8875  }
8876 
8877  CXXRecordDecl *RecordDef
8878  = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8879  if (!RecordDef) {
8880  // C++ [temp.explicit]p3:
8881  // A definition of a member class of a class template shall be in scope
8882  // at the point of an explicit instantiation of the member class.
8883  CXXRecordDecl *Def
8884  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8885  if (!Def) {
8886  Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8887  << 0 << Record->getDeclName() << Record->getDeclContext();
8888  Diag(Pattern->getLocation(), diag::note_forward_declaration)
8889  << Pattern;
8890  return true;
8891  } else {
8892  if (InstantiateClass(NameLoc, Record, Def,
8893  getTemplateInstantiationArgs(Record),
8894  TSK))
8895  return true;
8896 
8897  RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8898  if (!RecordDef)
8899  return true;
8900  }
8901  }
8902 
8903  // Instantiate all of the members of the class.
8904  InstantiateClassMembers(NameLoc, RecordDef,
8905  getTemplateInstantiationArgs(Record), TSK);
8906 
8908  MarkVTableUsed(NameLoc, RecordDef, true);
8909 
8910  // FIXME: We don't have any representation for explicit instantiations of
8911  // member classes. Such a representation is not needed for compilation, but it
8912  // should be available for clients that want to see all of the declarations in
8913  // the source code.
8914  return TagD;
8915 }
8916 
8918  SourceLocation ExternLoc,
8919  SourceLocation TemplateLoc,
8920  Declarator &D) {
8921  // Explicit instantiations always require a name.
8922  // TODO: check if/when DNInfo should replace Name.
8923  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8924  DeclarationName Name = NameInfo.getName();
8925  if (!Name) {
8926  if (!D.isInvalidType())
8928  diag::err_explicit_instantiation_requires_name)
8929  << D.getDeclSpec().getSourceRange()
8930  << D.getSourceRange();
8931 
8932  return true;
8933  }
8934 
8935  // The scope passed in may not be a decl scope. Zip up the scope tree until
8936  // we find one that is.
8937  while ((S->getFlags() & Scope::DeclScope) == 0 ||
8938  (S->getFlags() & Scope::TemplateParamScope) != 0)
8939  S = S->getParent();
8940 
8941  // Determine the type of the declaration.
8942  TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8943  QualType R = T->getType();
8944  if (R.isNull())
8945  return true;
8946 
8947  // C++ [dcl.stc]p1:
8948  // A storage-class-specifier shall not be specified in [...] an explicit
8949  // instantiation (14.7.2) directive.
8951  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8952  << Name;
8953  return true;
8954  } else if (D.getDeclSpec().getStorageClassSpec()
8956  // Complain about then remove the storage class specifier.
8957  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8959 
8961  }
8962 
8963  // C++0x [temp.explicit]p1:
8964  // [...] An explicit instantiation of a function template shall not use the
8965  // inline or constexpr specifiers.
8966  // Presumably, this also applies to member functions of class templates as
8967  // well.
8968  if (D.getDeclSpec().isInlineSpecified())
8970  getLangOpts().CPlusPlus11 ?
8971  diag::err_explicit_instantiation_inline :
8972  diag::warn_explicit_instantiation_inline_0x)
8975  // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8976  // not already specified.
8978  diag::err_explicit_instantiation_constexpr);
8979 
8980  // A deduction guide is not on the list of entities that can be explicitly
8981  // instantiated.
8983  Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8984  << /*explicit instantiation*/ 0;
8985  return true;
8986  }
8987 
8988  // C++0x [temp.explicit]p2:
8989  // There are two forms of explicit instantiation: an explicit instantiation
8990  // definition and an explicit instantiation declaration. An explicit
8991  // instantiation declaration begins with the extern keyword. [...]
8995 
8996  LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
8997  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
8998 
8999  if (!R->isFunctionType()) {
9000  // C++ [temp.explicit]p1:
9001  // A [...] static data member of a class template can be explicitly
9002  // instantiated from the member definition associated with its class
9003  // template.
9004  // C++1y [temp.explicit]p1:
9005  // A [...] variable [...] template specialization can be explicitly
9006  // instantiated from its template.
9007  if (Previous.isAmbiguous())
9008  return true;
9009 
9010  VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9011  VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9012 
9013  if (!PrevTemplate) {
9014  if (!Prev || !Prev->isStaticDataMember()) {
9015  // We expect to see a data data member here.
9016  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9017  << Name;
9018  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9019  P != PEnd; ++P)
9020  Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9021  return true;
9022  }
9023 
9024  if (!Prev->getInstantiatedFromStaticDataMember()) {
9025  // FIXME: Check for explicit specialization?
9026  Diag(D.getIdentifierLoc(),
9027  diag::err_explicit_instantiation_data_member_not_instantiated)
9028  << Prev;
9029  Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9030  // FIXME: Can we provide a note showing where this was declared?
9031  return true;
9032  }
9033  } else {
9034  // Explicitly instantiate a variable template.
9035 
9036  // C++1y [dcl.spec.auto]p6:
9037  // ... A program that uses auto or decltype(auto) in a context not
9038  // explicitly allowed in this section is ill-formed.
9039  //
9040  // This includes auto-typed variable template instantiations.
9041  if (R->isUndeducedType()) {
9042  Diag(T->getTypeLoc().getLocStart(),
9043  diag::err_auto_not_allowed_var_inst);
9044  return true;
9045  }
9046 
9048  // C++1y [temp.explicit]p3:
9049  // If the explicit instantiation is for a variable, the unqualified-id
9050  // in the declaration shall be a template-id.
9051  Diag(D.getIdentifierLoc(),
9052  diag::err_explicit_instantiation_without_template_id)
9053  << PrevTemplate;
9054  Diag(PrevTemplate->getLocation(),
9055  diag::note_explicit_instantiation_here);
9056  return true;
9057  }
9058 
9059  // Translate the parser's template argument list into our AST format.
9060  TemplateArgumentListInfo TemplateArgs =
9062 
9063  DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9064  D.getIdentifierLoc(), TemplateArgs);
9065  if (Res.isInvalid())
9066  return true;
9067 
9068  // Ignore access control bits, we don't need them for redeclaration
9069  // checking.
9070  Prev = cast<VarDecl>(Res.get());
9071  }
9072 
9073  // C++0x [temp.explicit]p2:
9074  // If the explicit instantiation is for a member function, a member class
9075  // or a static data member of a class template specialization, the name of
9076  // the class template specialization in the qualified-id for the member
9077  // name shall be a simple-template-id.
9078  //
9079  // C++98 has the same restriction, just worded differently.
9080  //
9081  // This does not apply to variable template specializations, where the
9082  // template-id is in the unqualified-id instead.
9083  if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9084  Diag(D.getIdentifierLoc(),
9085  diag::ext_explicit_instantiation_without_qualified_id)
9086  << Prev << D.getCXXScopeSpec().getRange();
9087 
9088  // Check the scope of this explicit instantiation.
9089  CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
9090 
9091  // Verify that it is okay to explicitly instantiate here.
9094  bool HasNoEffect = false;
9095  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9096  PrevTSK, POI, HasNoEffect))
9097  return true;
9098 
9099  if (!HasNoEffect) {
9100  // Instantiate static data member or variable template.
9101  Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9102  if (PrevTemplate) {
9103  // Merge attributes.
9105  ProcessDeclAttributeList(S, Prev, Attr);
9106  }
9108  InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9109  }
9110 
9111  // Check the new variable specialization against the parsed input.
9112  if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9113  Diag(T->getTypeLoc().getLocStart(),
9114  diag::err_invalid_var_template_spec_type)
9115  << 0 << PrevTemplate << R << Prev->getType();
9116  Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9117  << 2 << PrevTemplate->getDeclName();
9118  return true;
9119  }
9120 
9121  // FIXME: Create an ExplicitInstantiation node?
9122  return (Decl*) nullptr;
9123  }
9124 
9125  // If the declarator is a template-id, translate the parser's template
9126  // argument list into our AST format.
9127  bool HasExplicitTemplateArgs = false;
9128  TemplateArgumentListInfo TemplateArgs;
9130  TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9131  HasExplicitTemplateArgs = true;
9132  }
9133 
9134  // C++ [temp.explicit]p1:
9135  // A [...] function [...] can be explicitly instantiated from its template.
9136  // A member function [...] of a class template can be explicitly
9137  // instantiated from the member definition associated with its class
9138  // template.
9139  UnresolvedSet<8> TemplateMatches;
9140  FunctionDecl *NonTemplateMatch = nullptr;
9142  TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9143  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9144  P != PEnd; ++P) {
9145  NamedDecl *Prev = *P;
9146  if (!HasExplicitTemplateArgs) {
9147  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9148  QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9149  /*AdjustExceptionSpec*/true);
9150  if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9151  if (Method->getPrimaryTemplate()) {
9152  TemplateMatches.addDecl(Method, P.getAccess());
9153  } else {
9154  // FIXME: Can this assert ever happen? Needs a test.
9155  assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9156  NonTemplateMatch = Method;
9157  }
9158  }
9159  }
9160  }
9161 
9162  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9163  if (!FunTmpl)
9164  continue;
9165 
9166  TemplateDeductionInfo Info(FailedCandidates.getLocation());
9167  FunctionDecl *Specialization = nullptr;
9168  if (TemplateDeductionResult TDK
9169  = DeduceTemplateArguments(FunTmpl,
9170  (HasExplicitTemplateArgs ? &TemplateArgs
9171  : nullptr),
9172  R, Specialization, Info)) {
9173  // Keep track of almost-matches.
9174  FailedCandidates.addCandidate()
9175  .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9176  MakeDeductionFailureInfo(Context, TDK, Info));
9177  (void)TDK;
9178  continue;
9179  }
9180 
9181  // Target attributes are part of the cuda function signature, so
9182  // the cuda target of the instantiated function must match that of its
9183  // template. Given that C++ template deduction does not take
9184  // target attributes into account, we reject candidates here that
9185  // have a different target.
9186  if (LangOpts.CUDA &&
9187  IdentifyCUDATarget(Specialization,
9188  /* IgnoreImplicitHDAttributes = */ true) !=
9189  IdentifyCUDATarget(Attr)) {
9190  FailedCandidates.addCandidate().set(
9191  P.getPair(), FunTmpl->getTemplatedDecl(),
9192  MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9193  continue;
9194  }
9195 
9196  TemplateMatches.addDecl(Specialization, P.getAccess());
9197  }
9198 
9199  FunctionDecl *Specialization = NonTemplateMatch;
9200  if (!Specialization) {
9201  // Find the most specialized function template specialization.
9202  UnresolvedSetIterator Result = getMostSpecialized(
9203  TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9204  D.getIdentifierLoc(),
9205  PDiag(diag::err_explicit_instantiation_not_known) << Name,
9206  PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9207  PDiag(diag::note_explicit_instantiation_candidate));
9208 
9209  if (Result == TemplateMatches.end())
9210  return true;
9211 
9212  // Ignore access control bits, we don't need them for redeclaration checking.
9213  Specialization = cast<FunctionDecl>(*Result);
9214  }
9215 
9216  // C++11 [except.spec]p4
9217  // In an explicit instantiation an exception-specification may be specified,
9218  // but is not required.
9219  // If an exception-specification is specified in an explicit instantiation
9220  // directive, it shall be compatible with the exception-specifications of
9221  // other declarations of that function.
9222  if (auto *FPT = R->getAs<FunctionProtoType>())
9223  if (FPT->hasExceptionSpec()) {
9224  unsigned DiagID =
9225  diag::err_mismatched_exception_spec_explicit_instantiation;
9226  if (getLangOpts().MicrosoftExt)
9227  DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9228  bool Result = CheckEquivalentExceptionSpec(
9229  PDiag(DiagID) << Specialization->getType(),
9230  PDiag(diag::note_explicit_instantiation_here),
9231  Specialization->getType()->getAs<FunctionProtoType>(),
9232  Specialization->getLocation(), FPT, D.getLocStart());
9233  // In Microsoft mode, mismatching exception specifications just cause a
9234  // warning.
9235  if (!getLangOpts().MicrosoftExt && Result)
9236  return true;
9237  }
9238 
9239  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9240  Diag(D.getIdentifierLoc(),
9241  diag::err_explicit_instantiation_member_function_not_instantiated)
9242  << Specialization
9243  << (Specialization->getTemplateSpecializationKind() ==
9245  Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9246  return true;
9247  }
9248 
9249  FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9250  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9251  PrevDecl = Specialization;
9252 
9253  if (PrevDecl) {
9254  bool HasNoEffect = false;
9255  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9256  PrevDecl,
9257  PrevDecl->getTemplateSpecializationKind(),
9258  PrevDecl->getPointOfInstantiation(),
9259  HasNoEffect))
9260  return true;
9261 
9262  // FIXME: We may still want to build some representation of this
9263  // explicit specialization.
9264  if (HasNoEffect)
9265  return (Decl*) nullptr;
9266  }
9267 
9268  if (Attr)
9269  ProcessDeclAttributeList(S, Specialization, Attr);
9270 
9271  // In MSVC mode, dllimported explicit instantiation definitions are treated as
9272  // instantiation declarations.
9274  Specialization->hasAttr<DLLImportAttr>() &&
9275  Context.getTargetInfo().getCXXABI().isMicrosoft())
9277 
9278  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9279 
9280  if (Specialization->isDefined()) {
9281  // Let the ASTConsumer know that this function has been explicitly
9282  // instantiated now, and its linkage might have changed.
9283  Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9284  } else if (TSK == TSK_ExplicitInstantiationDefinition)
9285  InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9286 
9287  // C++0x [temp.explicit]p2:
9288  // If the explicit instantiation is for a member function, a member class
9289  // or a static data member of a class template specialization, the name of
9290  // the class template specialization in the qualified-id for the member
9291  // name shall be a simple-template-id.
9292  //
9293  // C++98 has the same restriction, just worded differently.
9294  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9295  if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9296  D.getCXXScopeSpec().isSet() &&
9298  Diag(D.getIdentifierLoc(),
9299  diag::ext_explicit_instantiation_without_qualified_id)
9300  << Specialization << D.getCXXScopeSpec().getRange();
9301 
9303  FunTmpl? (NamedDecl *)FunTmpl
9304  : Specialization->getInstantiatedFromMemberFunction(),
9305  D.getIdentifierLoc(),
9306  D.getCXXScopeSpec().isSet());
9307 
9308  // FIXME: Create some kind of ExplicitInstantiationDecl here.
9309  return (Decl*) nullptr;
9310 }
9311 
9312 TypeResult
9313 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9314  const CXXScopeSpec &SS, IdentifierInfo *Name,
9315  SourceLocation TagLoc, SourceLocation NameLoc) {
9316  // This has to hold, because SS is expected to be defined.
9317  assert(Name && "Expected a name in a dependent tag");
9318 
9319  NestedNameSpecifier *NNS = SS.getScopeRep();
9320  if (!NNS)
9321  return true;
9322 
9324 
9325  if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9326  Diag(NameLoc, diag::err_dependent_tag_decl)
9327  << (TUK == TUK_Definition) << Kind << SS.getRange();
9328  return true;
9329  }
9330 
9331  // Create the resulting type.
9333  QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9334 
9335  // Create type-source location information for this type.
9336  TypeLocBuilder TLB;
9338  TL.setElaboratedKeywordLoc(TagLoc);
9339  TL.setQualifierLoc(SS.getWithLocInContext(Context));
9340  TL.setNameLoc(NameLoc);
9341  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9342 }
9343 
9344 TypeResult
9346  const CXXScopeSpec &SS, const IdentifierInfo &II,
9347  SourceLocation IdLoc) {
9348  if (SS.isInvalid())
9349  return true;
9350 
9351  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9352  Diag(TypenameLoc,
9353  getLangOpts().CPlusPlus11 ?
9354  diag::warn_cxx98_compat_typename_outside_of_template :
9355  diag::ext_typename_outside_of_template)
9356  << FixItHint::CreateRemoval(TypenameLoc);
9357 
9358  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9359  QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9360  TypenameLoc, QualifierLoc, II, IdLoc);
9361  if (T.isNull())
9362  return true;
9363 
9364  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9365  if (isa<DependentNameType>(T)) {
9367  TL.setElaboratedKeywordLoc(TypenameLoc);
9368  TL.setQualifierLoc(QualifierLoc);
9369  TL.setNameLoc(IdLoc);
9370  } else {
9372  TL.setElaboratedKeywordLoc(TypenameLoc);
9373  TL.setQualifierLoc(QualifierLoc);
9374  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9375  }
9376 
9377  return CreateParsedType(T, TSI);
9378 }
9379 
9380 TypeResult
9382  SourceLocation TypenameLoc,
9383  const CXXScopeSpec &SS,
9384  SourceLocation TemplateKWLoc,
9385  TemplateTy TemplateIn,
9386  IdentifierInfo *TemplateII,
9387  SourceLocation TemplateIILoc,
9388  SourceLocation LAngleLoc,
9389  ASTTemplateArgsPtr TemplateArgsIn,
9390  SourceLocation RAngleLoc) {
9391  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9392  Diag(TypenameLoc,
9393  getLangOpts().CPlusPlus11 ?
9394  diag::warn_cxx98_compat_typename_outside_of_template :
9395  diag::ext_typename_outside_of_template)
9396  << FixItHint::CreateRemoval(TypenameLoc);
9397 
9398  // Strangely, non-type results are not ignored by this lookup, so the
9399  // program is ill-formed if it finds an injected-class-name.
9400  if (TypenameLoc.isValid()) {
9401  auto *LookupRD =
9402  dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9403  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9404  Diag(TemplateIILoc,
9405  diag::ext_out_of_line_qualified_id_type_names_constructor)
9406  << TemplateII << 0 /*injected-class-name used as template name*/
9407  << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9408  }
9409  }
9410 
9411  // Translate the parser's template argument list in our AST format.
9412  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9413  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9414 
9415  TemplateName Template = TemplateIn.get();
9416  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9417  // Construct a dependent template specialization type.
9418  assert(DTN && "dependent template has non-dependent name?");
9419  assert(DTN->getQualifier() == SS.getScopeRep());
9421  DTN->getQualifier(),
9422  DTN->getIdentifier(),
9423  TemplateArgs);
9424 
9425  // Create source-location information for this type.
9426  TypeLocBuilder Builder;
9429  SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9430  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9431  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9432  SpecTL.setTemplateNameLoc(TemplateIILoc);
9433  SpecTL.setLAngleLoc(LAngleLoc);
9434  SpecTL.setRAngleLoc(RAngleLoc);
9435  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9436  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9437  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9438  }
9439 
9440  QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9441  if (T.isNull())
9442  return true;
9443 
9444  // Provide source-location information for the template specialization type.
9445  TypeLocBuilder Builder;
9447  = Builder.push<TemplateSpecializationTypeLoc>(T);
9448  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9449  SpecTL.setTemplateNameLoc(TemplateIILoc);
9450  SpecTL.setLAngleLoc(LAngleLoc);
9451  SpecTL.setRAngleLoc(RAngleLoc);
9452  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9453  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9454 
9455  T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9456  ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9457  TL.setElaboratedKeywordLoc(TypenameLoc);
9458  TL.setQualifierLoc(SS.getWithLocInContext(Context));
9459 
9460  TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9461  return CreateParsedType(T, TSI);
9462 }
9463 
9464 
9465 /// Determine whether this failed name lookup should be treated as being
9466 /// disabled by a usage of std::enable_if.
9468  SourceRange &CondRange, Expr *&Cond) {
9469  // We must be looking for a ::type...
9470  if (!II.isStr("type"))
9471  return false;
9472 
9473  // ... within an explicitly-written template specialization...
9474  if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9475  return false;
9476  TypeLoc EnableIfTy = NNS.getTypeLoc();
9477  TemplateSpecializationTypeLoc EnableIfTSTLoc =
9478  EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9479  if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9480  return false;
9481  const TemplateSpecializationType *EnableIfTST =
9482  cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
9483 
9484  // ... which names a complete class template declaration...
9485  const TemplateDecl *EnableIfDecl =
9486  EnableIfTST->getTemplateName().getAsTemplateDecl();
9487  if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9488  return false;
9489 
9490  // ... called "enable_if".
9491  const IdentifierInfo *EnableIfII =
9492  EnableIfDecl->getDeclName().getAsIdentifierInfo();
9493  if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9494  return false;
9495 
9496  // Assume the first template argument is the condition.
9497  CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9498 
9499  // Dig out the condition.
9500  Cond = nullptr;
9501  if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9503  return true;
9504 
9505  Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9506 
9507  // Ignore Boolean literals; they add no value.
9508  if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9509  Cond = nullptr;
9510 
9511  return true;
9512 }
9513 
9514 /// \brief Build the type that describes a C++ typename specifier,
9515 /// e.g., "typename T::type".
9516 QualType
9518  SourceLocation KeywordLoc,
9519  NestedNameSpecifierLoc QualifierLoc,
9520  const IdentifierInfo &II,
9521  SourceLocation IILoc) {
9522  CXXScopeSpec SS;
9523  SS.Adopt(QualifierLoc);
9524 
9525  DeclContext *Ctx = computeDeclContext(SS);
9526  if (!Ctx) {
9527  // If the nested-name-specifier is dependent and couldn't be
9528  // resolved to a type, build a typename type.
9529  assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9530  return Context.getDependentNameType(Keyword,
9531  QualifierLoc.getNestedNameSpecifier(),
9532  &II);
9533  }
9534 
9535  // If the nested-name-specifier refers to the current instantiation,
9536  // the "typename" keyword itself is superfluous. In C++03, the
9537  // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9538  // allows such extraneous "typename" keywords, and we retroactively
9539  // apply this DR to C++03 code with only a warning. In any case we continue.
9540 
9541  if (RequireCompleteDeclContext(SS, Ctx))
9542  return QualType();
9543 
9544  DeclarationName Name(&II);
9545  LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9546  LookupQualifiedName(Result, Ctx, SS);
9547  unsigned DiagID = 0;
9548  Decl *Referenced = nullptr;
9549  switch (Result.getResultKind()) {
9550  case LookupResult::NotFound: {
9551  // If we're looking up 'type' within a template named 'enable_if', produce
9552  // a more specific diagnostic.
9553  SourceRange CondRange;
9554  Expr *Cond = nullptr;
9555  if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9556  // If we have a condition, narrow it down to the specific failed
9557  // condition.
9558  if (Cond) {
9559  Expr *FailedCond;
9560  std::string FailedDescription;
9561  std::tie(FailedCond, FailedDescription) =
9562  findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
9563 
9564  Diag(FailedCond->getExprLoc(),
9565  diag::err_typename_nested_not_found_requirement)
9566  << FailedDescription
9567  << FailedCond->getSourceRange();
9568  return QualType();
9569  }
9570 
9571  Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9572  << Ctx << CondRange;
9573  return QualType();
9574  }
9575 
9576  DiagID = diag::err_typename_nested_not_found;
9577  break;
9578  }
9579 
9581  // We found a using declaration that is a value. Most likely, the using
9582  // declaration itself is meant to have the 'typename' keyword.
9583  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9584  IILoc);
9585  Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9586  << Name << Ctx << FullRange;
9587  if (UnresolvedUsingValueDecl *Using
9588  = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9589  SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9590  Diag(Loc, diag::note_using_value_decl_missing_typename)
9591  << FixItHint::CreateInsertion(Loc, "typename ");
9592  }
9593  }
9594  // Fall through to create a dependent typename type, from which we can recover
9595  // better.
9596  LLVM_FALLTHROUGH;
9597 
9599  // Okay, it's a member of an unknown instantiation.
9600  return Context.getDependentNameType(Keyword,
9601  QualifierLoc.getNestedNameSpecifier(),
9602  &II);
9603 
9604  case LookupResult::Found:
9605  if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9606  // C++ [class.qual]p2:
9607  // In a lookup in which function names are not ignored and the
9608  // nested-name-specifier nominates a class C, if the name specified
9609  // after the nested-name-specifier, when looked up in C, is the
9610  // injected-class-name of C [...] then the name is instead considered
9611  // to name the constructor of class C.
9612  //
9613  // Unlike in an elaborated-type-specifier, function names are not ignored
9614  // in typename-specifier lookup. However, they are ignored in all the
9615  // contexts where we form a typename type with no keyword (that is, in
9616  // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9617  //
9618  // FIXME: That's not strictly true: mem-initializer-id lookup does not
9619  // ignore functions, but that appears to be an oversight.
9620  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9621  auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9622  if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9623  FoundRD->isInjectedClassName() &&
9624  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9625  Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9626  << &II << 1 << 0 /*'typename' keyword used*/;
9627 
9628  // We found a type. Build an ElaboratedType, since the
9629  // typename-specifier was just sugar.
9630  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9631  return Context.getElaboratedType(Keyword,
9632  QualifierLoc.getNestedNameSpecifier(),
9633  Context.getTypeDeclType(Type));
9634  }
9635 
9636  // C++ [dcl.type.simple]p2:
9637  // A type-specifier of the form
9638  // typename[opt] nested-name-specifier[opt] template-name
9639  // is a placeholder for a deduced class type [...].
9640  if (getLangOpts().CPlusPlus17) {
9641  if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9642  return Context.getElaboratedType(
9643  Keyword, QualifierLoc.getNestedNameSpecifier(),
9645  QualType(), false));
9646  }
9647  }
9648 
9649  DiagID = diag::err_typename_nested_not_type;
9650  Referenced = Result.getFoundDecl();
9651  break;
9652 
9654  DiagID = diag::err_typename_nested_not_type;
9655  Referenced = *Result.begin();
9656  break;
9657 
9659  return QualType();
9660  }
9661 
9662  // If we get here, it's because name lookup did not find a
9663  // type. Emit an appropriate diagnostic and return an error.
9664  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9665  IILoc);
9666  Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9667  if (Referenced)
9668  Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9669  << Name;
9670  return QualType();
9671 }
9672 
9673 namespace {
9674  // See Sema::RebuildTypeInCurrentInstantiation
9675  class CurrentInstantiationRebuilder
9676  : public TreeTransform<CurrentInstantiationRebuilder> {
9677  SourceLocation Loc;
9678  DeclarationName Entity;
9679 
9680  public:
9682 
9683  CurrentInstantiationRebuilder(Sema &SemaRef,
9684  SourceLocation Loc,
9685  DeclarationName Entity)
9687  Loc(Loc), Entity(Entity) { }
9688 
9689  /// \brief Determine whether the given type \p T has already been
9690  /// transformed.
9691  ///
9692  /// For the purposes of type reconstruction, a type has already been
9693  /// transformed if it is NULL or if it is not dependent.
9694  bool AlreadyTransformed(QualType T) {
9695  return T.isNull() || !T->isDependentType();
9696  }
9697 
9698  /// \brief Returns the location of the entity whose type is being
9699  /// rebuilt.
9700  SourceLocation getBaseLocation() { return Loc; }
9701 
9702  /// \brief Returns the name of the entity whose type is being rebuilt.
9703  DeclarationName getBaseEntity() { return Entity; }
9704 
9705  /// \brief Sets the "base" location and entity when that
9706  /// information is known based on another transformation.
9707  void setBase(SourceLocation Loc, DeclarationName Entity) {
9708  this->Loc = Loc;
9709  this->Entity = Entity;
9710  }
9711 
9712  ExprResult TransformLambdaExpr(LambdaExpr *E) {
9713  // Lambdas never need to be transformed.
9714  return E;
9715  }
9716  };
9717 } // end anonymous namespace
9718 
9719 /// \brief Rebuilds a type within the context of the current instantiation.
9720 ///
9721 /// The type \p T is part of the type of an out-of-line member definition of
9722 /// a class template (or class template partial specialization) that was parsed
9723 /// and constructed before we entered the scope of the class template (or
9724 /// partial specialization thereof). This routine will rebuild that type now
9725 /// that we have entered the declarator's scope, which may produce different
9726 /// canonical types, e.g.,
9727 ///
9728 /// \code
9729 /// template<typename T>
9730 /// struct X {
9731 /// typedef T* pointer;
9732 /// pointer data();
9733 /// };
9734 ///
9735 /// template<typename T>
9736 /// typename X<T>::pointer X<T>::data() { ... }
9737 /// \endcode
9738 ///
9739 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9740 /// since we do not know that we can look into X<T> when we parsed the type.
9741 /// This function will rebuild the type, performing the lookup of "pointer"
9742 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9743 /// as the canonical type of T*, allowing the return types of the out-of-line
9744 /// definition and the declaration to match.
9746  SourceLocation Loc,
9747  DeclarationName Name) {
9748  if (!T || !T->getType()->isDependentType())
9749  return T;
9750 
9751  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9752  return Rebuilder.TransformType(T);
9753 }
9754 
9756  CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9757  DeclarationName());
9758  return Rebuilder.TransformExpr(E);
9759 }
9760 
9762  if (SS.isInvalid())
9763  return true;
9764 
9765  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9766  CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9767  DeclarationName());
9768  NestedNameSpecifierLoc Rebuilt
9769  = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9770  if (!Rebuilt)
9771  return true;
9772 
9773  SS.Adopt(Rebuilt);
9774  return false;
9775 }
9776 
9777 /// \brief Rebuild the template parameters now that we know we're in a current
9778 /// instantiation.
9780  TemplateParameterList *Params) {
9781  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9782  Decl *Param = Params->getParam(I);
9783 
9784  // There is nothing to rebuild in a type parameter.
9785  if (isa<TemplateTypeParmDecl>(Param))
9786  continue;
9787 
9788  // Rebuild the template parameter list of a template template parameter.
9789  if (TemplateTemplateParmDecl *TTP
9790  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9791  if (RebuildTemplateParamsInCurrentInstantiation(
9792  TTP->getTemplateParameters()))
9793  return true;
9794 
9795  continue;
9796  }
9797 
9798  // Rebuild the type of a non-type template parameter.
9799  NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9800  TypeSourceInfo *NewTSI
9801  = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9802  NTTP->getLocation(),
9803  NTTP->getDeclName());
9804  if (!NewTSI)
9805  return true;
9806 
9807  if (NewTSI != NTTP->getTypeSourceInfo()) {
9808  NTTP->setTypeSourceInfo(NewTSI);
9809  NTTP->setType(NewTSI->getType());
9810  }
9811  }
9812 
9813  return false;
9814 }
9815 
9816 /// \brief Produces a formatted string that describes the binding of
9817 /// template parameters to template arguments.
9818 std::string
9820  const TemplateArgumentList &Args) {
9821  return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9822 }
9823 
9824 std::string
9826  const TemplateArgument *Args,
9827  unsigned NumArgs) {
9828  SmallString<128> Str;
9829  llvm::raw_svector_ostream Out(Str);
9830 
9831  if (!Params || Params->size() == 0 || NumArgs == 0)
9832  return std::string();
9833 
9834  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9835  if (I >= NumArgs)
9836  break;
9837 
9838  if (I == 0)
9839  Out << "[with ";
9840  else
9841  Out << ", ";
9842 
9843  if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9844  Out << Id->getName();
9845  } else {
9846  Out << '$' << I;
9847  }
9848 
9849  Out << " = ";
9850  Args[I].print(getPrintingPolicy(), Out);
9851  }
9852 
9853  Out << ']';
9854  return Out.str();
9855 }
9856 
9858  CachedTokens &Toks) {
9859  if (!FD)
9860  return;
9861 
9862  auto LPT = llvm::make_unique<LateParsedTemplate>();
9863 
9864  // Take tokens to avoid allocations
9865  LPT->Toks.swap(Toks);
9866  LPT->D = FnD;
9867  LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9868 
9869  FD->setLateTemplateParsed(true);
9870 }
9871 
9873  if (!FD)
9874  return;
9875  FD->setLateTemplateParsed(false);
9876 }
9877 
9879  DeclContext *DC = CurContext;
9880 
9881  while (DC) {
9882  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9883  const FunctionDecl *FD = RD->isLocalClass();
9884  return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9885  } else if (DC->isTranslationUnit() || DC->isNamespace())
9886  return false;
9887 
9888  DC = DC->getParent();
9889  }
9890  return false;
9891 }
9892 
9893 namespace {
9894 /// \brief Walk the path from which a declaration was instantiated, and check
9895 /// that every explicit specialization along that path is visible. This enforces
9896 /// C++ [temp.expl.spec]/6:
9897 ///
9898 /// If a template, a member template or a member of a class template is
9899 /// explicitly specialized then that specialization shall be declared before
9900 /// the first use of that specialization that would cause an implicit
9901 /// instantiation to take place, in every translation unit in which such a
9902 /// use occurs; no diagnostic is required.
9903 ///
9904 /// and also C++ [temp.class.spec]/1:
9905 ///
9906 /// A partial specialization shall be declared before the first use of a
9907 /// class template specialization that would make use of the partial
9908 /// specialization as the result of an implicit or explicit instantiation
9909 /// in every translation unit in which such a use occurs; no diagnostic is
9910 /// required.
9911 class ExplicitSpecializationVisibilityChecker {
9912  Sema &S;
9913  SourceLocation Loc;
9915 
9916 public:
9917  ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9918  : S(S), Loc(Loc) {}
9919 
9920  void check(NamedDecl *ND) {
9921  if (auto *FD = dyn_cast<FunctionDecl>(ND))
9922  return checkImpl(FD);
9923  if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9924  return checkImpl(RD);
9925  if (auto *VD = dyn_cast<VarDecl>(ND))
9926  return checkImpl(VD);
9927  if (auto *ED = dyn_cast<EnumDecl>(ND))
9928  return checkImpl(ED);
9929  }
9930 
9931 private:
9932  void diagnose(NamedDecl *D, bool IsPartialSpec) {
9933  auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9935  const bool Recover = true;
9936 
9937  // If we got a custom set of modules (because only a subset of the
9938  // declarations are interesting), use them, otherwise let
9939  // diagnoseMissingImport intelligently pick some.
9940  if (Modules.empty())
9941  S.diagnoseMissingImport(Loc, D, Kind, Recover);
9942  else
9943  S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9944  }
9945 
9946  // Check a specific declaration. There are three problematic cases:
9947  //
9948  // 1) The declaration is an explicit specialization of a template
9949  // specialization.
9950  // 2) The declaration is an explicit specialization of a member of an
9951  // templated class.
9952  // 3) The declaration is an instantiation of a template, and that template
9953  // is an explicit specialization of a member of a templated class.
9954  //
9955  // We don't need to go any deeper than that, as the instantiation of the
9956  // surrounding class / etc is not triggered by whatever triggered this
9957  // instantiation, and thus should be checked elsewhere.
9958  template<typename SpecDecl>
9959  void checkImpl(SpecDecl *Spec) {
9960  bool IsHiddenExplicitSpecialization = false;
9961  if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9962  IsHiddenExplicitSpecialization =
9963  Spec->getMemberSpecializationInfo()
9964  ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9965  : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
9966  } else {
9967  checkInstantiated(Spec);
9968  }
9969 
9970  if (IsHiddenExplicitSpecialization)
9971  diagnose(Spec->getMostRecentDecl(), false);
9972  }
9973 
9974  void checkInstantiated(FunctionDecl *FD) {
9975  if (auto *TD = FD->getPrimaryTemplate())
9976  checkTemplate(TD);
9977  }
9978 
9979  void checkInstantiated(CXXRecordDecl *RD) {
9980  auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9981  if (!SD)
9982  return;
9983 
9984  auto From = SD->getSpecializedTemplateOrPartial();
9985  if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9986  checkTemplate(TD);
9987  else if (auto *TD =
9988  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9989  if (!S.hasVisibleDeclaration(TD))
9990  diagnose(TD, true);
9991  checkTemplate(TD);
9992  }
9993  }
9994 
9995  void checkInstantiated(VarDecl *RD) {
9996  auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9997  if (!SD)
9998  return;
9999 
10000  auto From = SD->getSpecializedTemplateOrPartial();
10001  if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10002  checkTemplate(TD);
10003  else if (auto *TD =
10004  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10005  if (!S.hasVisibleDeclaration(TD))
10006  diagnose(TD, true);
10007  checkTemplate(TD);
10008  }
10009  }
10010 
10011  void checkInstantiated(EnumDecl *FD) {}
10012 
10013  template<typename TemplDecl>
10014  void checkTemplate(TemplDecl *TD) {
10015  if (TD->isMemberSpecialization()) {
10016  if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10017  diagnose(TD->getMostRecentDecl(), false);
10018  }
10019  }
10020 };
10021 } // end anonymous namespace
10022 
10024  if (!getLangOpts().Modules)
10025  return;
10026 
10027  ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10028 }
10029 
10030 /// \brief Check whether a template partial specialization that we've discovered
10031 /// is hidden, and produce suitable diagnostics if so.
10033  NamedDecl *Spec) {
10035  if (!hasVisibleDeclaration(Spec, &Modules))
10036  diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10037  MissingImportKind::PartialSpecialization,
10038  /*Recover*/true);
10039 }
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:265
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:5021
ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
Defines the clang::ASTContext interface.
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it&#39;s either not been deduced or was deduce...
Definition: Type.h:4387
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1546
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:565
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:3045
void setImplicit(bool I=true)
Definition: DeclBase.h:552
An instance of this class is created to represent a function declaration or definition.
Definition: Decl.h:1697
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:569
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:49
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
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.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
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.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:580
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2365
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:497
PtrTy get() const
Definition: Ownership.h:74
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2283
QualType getPointeeType() const
Definition: Type.h:2296
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:3727
A (possibly-)qualified type.
Definition: Type.h:653
Simple class containing the result of Sema::CorrectTypo.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:6837
void InstantiatedLocal(const Decl *D, Decl *Inst)
base_class_range bases()
Definition: DeclCXX.h:773
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion...
bool isArrayType() const
Definition: Type.h:5991
void setDefaultArgument(TypeSourceInfo *DefArg)
Set the default argument for this template parameter.
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMemberPointerType() const
Definition: Type.h:5973
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
static const TemplateArgument & getArgument(const TemplateArgument &A)
QualType getInjectedSpecializationType() const
Definition: Type.h:4665
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:478
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:1856
AttributeList * getNext() const
llvm::PointerUnion3< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:62
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1110
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:202
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:404
static CXXDependentScopeMemberExpr * Create(const ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1147
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2994
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:526
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:111
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:260
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
static UnresolvedLookupExpr * Create(const ASTContext &C, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool ADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.h:2781
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1443
Stmt - This represents one statement.
Definition: Stmt.h:66
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:938
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:685
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1637
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1457
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:6379
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4111
Provides information about an attempted template argument deduction, whose success or failure was des...
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:456
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:790
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 ...
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1009
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
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...
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
Microsoft&#39;s &#39;__super&#39; specifier, stored as a CXXRecordDecl* of the class it appeared in...
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2042
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:4849
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:344
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:87
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:270
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:4868
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:657
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1880
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1270
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isVariadic() const
Definition: Type.h:3615
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:2736
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Defines the C++ template declaration subclasses.
StringRef P
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition: Scope.h:371
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4401
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
Expr * getAsExpr() const
Retrieve the non-type template argument&#39;s expression.
Not a friend object.
Definition: DeclBase.h:1093
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1665
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:952
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:5891
void AddDecl(Decl *D)
Definition: Scope.h:281
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:2465
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
The base class of the type hierarchy.
Definition: Type.h:1351
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2153
Declaration of a variable template.
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:6111
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:64
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:505
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:45
void setSpecializationKind(TemplateSpecializationKind TSK)
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:133
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:671
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:95
A container of type source information.
Definition: Decl.h:86
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5629
bool isSuppressingDiagnostics() const
Determines whether this lookup is suppressing diagnostics.
Definition: Lookup.h:591
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module *> *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition: Sema.h:1567
TypeSourceInfo * getDefaultArgumentInfo() const
Retrieves the default argument&#39;s source information, if any.
An overloaded operator name, e.g., operator+.
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function is defined at all, including a deleted definition.
Definition: Decl.cpp:2605
void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo)
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...
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:446
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclBase.h:412
static void StripImplicitInstantiation(NamedDecl *D)
Strips various properties off an implicit instantiation that has just been explicitly specialized...
bool hasNext() const
Definition: Lookup.h:642
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:9804
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...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &Converted, bool UpdateArgsWithConversions=true)
Check that the given template arguments can be be provided to the given template, converting the argu...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2397
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
QualType getElementType() const
Definition: Type.h:2593
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:484
An identifier, stored as an IdentifierInfo*.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:125
unsigned getDepth() const
Get the nesting depth of the template parameter.
FriendDecl - Represents the declaration of a friend entity, which can be a function, a type, or a templated function or type.
Definition: DeclFriend.h:54
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10640
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:806
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:255
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1752
bool isEnumeralType() const
Definition: Type.h:6019
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6305
bool hasDefaultArg() const
hasDefaultArg - Determines whether this parameter has a default argument, either parsed or not...
Definition: Decl.cpp:2541
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:552
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:57
Extra information about a function prototype.
Definition: Type.h:3387
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:45
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const
Produce a unique representation of the given statement.
Represents a C++17 deduced template specialization type.
Definition: Type.h:4437
Represents a variable template specialization, which refers to a variable template with a given set o...
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1092
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:422
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:10559
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:573
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:173
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
bool isAmbiguous() const
Definition: Lookup.h:304
A namespace, stored as a NamespaceDecl*.
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2034
bool isInvalidDecl() const
Definition: DeclBase.h:546
bool isChar32Type() const
Definition: Type.cpp:1772
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:68
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl< TemplateArgument > &Converted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:213
static Optional< unsigned > getExpandedPackSize(NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:629
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1513
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:4256
Defines the clang::Expr interface and subclasses for C++ expressions.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:315
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
AttributeList * getList() const
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2014
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier...
Definition: TypeLoc.h:508
The collection of all-type qualifiers we support.
Definition: Type.h:152
bool isLValueOnePastTheEnd() const
Definition: APValue.cpp:558
Information about a template-id annotation token.
PipeType - OpenCL20.
Definition: Type.h:5648
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:6047
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:615
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 SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1398
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2865
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3488
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
Scope * getTemplateParamParent()
Definition: Scope.h:259
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:962
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1111
bool isWideCharType() const
Definition: Type.cpp:1759
One of these records is kept for each identifier that is lexed.
Represents a class template specialization, which refers to a class template with a given set of temp...
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:859
TemplateName getUnderlying() const
Definition: TemplateName.h:348
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:7489
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:59
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1427
unsigned getDepth() const
Retrieve the depth of the template parameter.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter &#39;PrevD...
bool isConst() const
Definition: DeclCXX.h:2006
void replace(NamedDecl *D)
Replaces the current entry with the given one, preserving the access bits.
Definition: Lookup.h:664
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Represents a class type in Objective C.
Definition: Type.h:5184
QualType getPointeeType() const
Definition: Type.h:2400
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:330
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:713
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
A C++ nested-name-specifier augmented with source location information.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7393
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:422
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3496
static NamedDecl * isAcceptableTemplateName(ASTContext &Context, NamedDecl *Orig, bool AllowFunctionTemplates)
Determine whether the declaration found is acceptable as the name of a template and, if so, return that template declaration.
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3844
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:501
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:72
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1653
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3609
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3200
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:4563
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We&#39;ve found a use of a templated declaration that would trigger an implicit instantiation.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SourceLocation getLocation() const
Retrieve the location of the template argument.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType) const
SourceLocation getLocation() const
Fetches the primary location of the argument.
Definition: TemplateBase.h:482
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:921
bool isNamespace() const
Definition: DeclBase.h:1413
An operation on a type.
Definition: TypeVisitor.h:65
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1566
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:245
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3725
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:942
bool isReferenceType() const
Definition: Type.h:5954
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2064
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:4312
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
A non-type template parameter, stored as an expression.
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1455
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1439
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, bool IsExplicit, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation)
Definition: DeclCXX.cpp:1616
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1877
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
LookupResultKind getResultKind() const
Definition: Lookup.h:324
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, const SmallVectorImpl< TemplateArgument > &Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void ClearStorageClassSpecs()
Definition: DeclSpec.h:459
The type of a non-type template parameter.
Definition: Sema.h:6528
ParsedType getAsType() const
Retrieve the template type argument&#39;s type.
SourceRange getSourceRange() const LLVM_READONLY
Fetches the full source range of the argument.
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:172
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:417
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6219
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:41
A user-defined literal name, e.g., operator "" _i.
void setDefaultArgument(Expr *DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:107
bool isInvalidType() const
Definition: DeclSpec.h:2412
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:507
DeclClass * getAsSingle() const
Definition: Lookup.h:510
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:2387
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e.g.
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.
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, IdentifierInfo *Name)
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:910
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1615
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2484
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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:558
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1671
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:522
Represents the results of name lookup.
Definition: Lookup.h:32
PtrTy get() const
Definition: Ownership.h:162
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2177
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:676
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
TagKind getTagKind() const
Definition: Decl.h:3156
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
A convenient class for passing around template argument information.
Definition: TemplateBase.h:546
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true)
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3782
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:2377
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1113
TypeDecl - Represents a declaration of a type.
Definition: Decl.h:2760
std::string getAsString(ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:545
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2453
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr *> &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1431
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
const Type * getClass() const
Definition: Type.h:2536
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization...
Definition: Decl.h:3469
bool isNull() const
Definition: TypeLoc.h:118
CXXRecordDecl * getDecl() const
Definition: Type.cpp:3159
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3341
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:538
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2465
void setSpecializationKind(TemplateSpecializationKind TSK)
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, const ASTContext *Context=nullptr) const
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5718
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1153
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:2157
NullPointerValueKind
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Definition: Decl.h:3183
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
bool isNoreturnSpecified() const
Definition: DeclSpec.h:572
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:820
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1580
const LangOptions & getLangOpts() const
Definition: Sema.h:1193
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1661
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:748
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1856
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:273
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization, retrieves the function from which it was instantiated.
Definition: Decl.cpp:3204
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3202
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1419
static bool CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &Converted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
Represents a linkage specification.
Definition: DeclCXX.h:2743
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:501
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:429
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:6400
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:500
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2106
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location...
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:869
QualType getElementType() const
Definition: Type.h:2890
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:7230
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:2874
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1536
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3327
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:6389
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1197
Represents a K&R-style &#39;int foo()&#39; function, which has no information available about its arguments...
Definition: Type.h:3233
NodeId Parent
Definition: ASTDiff.cpp:192
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:216
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
static Sema::TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, const TemplateArgument &Param, TemplateArgument Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
void print(const PrintingPolicy &Policy, raw_ostream &Out) const
Print this template argument to the given output stream.
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &Converted)
bool hasAttr() const
Definition: DeclBase.h:535
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1848
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:274
TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x alias-declaration.
Definition: Decl.h:2918
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &Converted, CheckTemplateArgumentKind CTAK=CTAK_Specified)
Check that the given template argument corresponds to the given template parameter.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3268
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:15025
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2787
bool hasLValuePath() const
Definition: APValue.cpp:568
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1386
static TypeSourceInfo * SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, SmallVectorImpl< TemplateArgument > &Converted)
Substitute template arguments into the default template argument for the given template type paramete...
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...
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:290
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...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:540
Specifies that the expression should never be value-dependent.
Definition: Expr.h:698
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
void addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition: Template.h:127
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5793
SourceRange getRange() const
Definition: DeclSpec.h:68
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:6371
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2185
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:264
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2161
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:2772
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:432
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
QualType getElementType() const
Definition: Type.h:2236
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1560
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2133
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:627
Expr - This represents one expression.
Definition: Expr.h:106
Defines the clang::LangOptions interface.
StringRef getKindName() const
Definition: Decl.h:3152
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs)
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1423
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:2990
QualType getPointeeType() const
Definition: Type.h:2440
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:104
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4723
bool isExplicitSpecified() const
Definition: DeclSpec.h:569
Expr * getAssociatedConstraints() const
Definition: DeclTemplate.h:445
int Id
Definition: ASTDiff.cpp:191
const FunctionProtoType * T
StateNode * Previous
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
Declaration of a template type parameter.
unsigned getIndex() const
Definition: Type.h:4219
DeclContext * getEntity() const
Definition: Scope.h:319
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6368
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:7363
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4705
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:68
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:86
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:1973
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
bool isChar16Type() const
Definition: Type.cpp:1766
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:455
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:1690
bool isNullPtrType() const
Definition: Type.h:6182
bool isFileContext() const
Definition: DeclBase.h:1401
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
DeclContext * getDeclContext()
Definition: DeclBase.h:425
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:731
bool hasEllipsis() const
Definition: DeclSpec.h:2423
bool isConstexprSpecified() const
Definition: DeclSpec.h:703
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2452
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:883
void NoteAllFoundTemplates(TemplateName Name)
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:1956
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:201
Represents a C++ template name within the type system.
Definition: TemplateName.h:178
static DependentScopeDeclRefExpr * Create(const ASTContext &C, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:421
Represents the type decltype(expr) (C++11).
Definition: Type.h:3852
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given function template specialization.
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:454
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this...
A namespace alias, stored as a NamespaceAliasDecl*.
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:481
int Depth
Definition: ASTDiff.cpp:191
void setLateTemplateParsed(bool ILT=true)
Definition: Decl.h:2001
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:992
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.h:1956
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn&#39;t a simple identifier.
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:618
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...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:21
QualType getType() const
Definition: Expr.h:128
bool isFunctionOrMethod() const
Definition: DeclBase.h:1384
StorageClass
Storage classes.
Definition: Specifiers.h:203
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1415
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...
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
A unary type transform, which is a type constructed from another.
Definition: Type.h:3895
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:311
Declaration of an alias template.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1335
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:42
TemplateNameKind ActOnDependentTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a dependent template name.
bool isInvalid() const
Definition: Ownership.h:158
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn&#39;t, and suggest a module import th...
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1717
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:1333
Represents a GCC generic vector type.
Definition: Type.h:2914
void setLocation(SourceLocation L)
Definition: DeclBase.h:417
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization, retrieves the member specialization information.
Definition: DeclCXX.cpp:1364
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2466
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3838
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1041
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4361
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization)
ValueDecl * getDecl()
Definition: Expr.h:1041
BuiltinTemplateKind getBuiltinTemplateKind() const
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1382
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:1347
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:149
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2073
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList *> TPLists)
Definition: Decl.cpp:3791
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLock is not of the desire...
Definition: TypeLoc.h:2344
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause)
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:1102
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5751
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:122
bool isEnum() const
Definition: Decl.h:3166
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
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...
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:3894
RecordDecl * getDecl() const
Definition: Type.h:3986
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:573
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
void addAttr(Attr *A)
Definition: DeclBase.h:484
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument...
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:217
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter...
CanQualType OverloadTy
Definition: ASTContext.h:1013
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template.
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1708
#define false
Definition: stdbool.h:33
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply...
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:180
Kind
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:144
const LValueBase getLValueBase() const
Definition: APValue.cpp:553
param_type_range param_types() const
Definition: Type.h:3637
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:208
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2169
Represents the parsed form of a C++ template argument.
A stack object to be created when performing template instantiation.
Definition: Sema.h:7267
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3500
SCS getStorageClassSpec() const
Definition: DeclSpec.h:445
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
ASTContext & getASTContext() const
Definition: Sema.h:1200
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList *> FriendTypeTPLists=None)
Definition: DeclFriend.cpp:35
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
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:3276
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3201
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4002
Represents typeof(type), a GCC extension.
Definition: Type.h:3825
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5384
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1874
void setBraceRange(SourceRange R)
Definition: Decl.h:3073
Attr * clone(ASTContext &C) const
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &Converted)
Checks whether the given template argument is the address of an object or function according to C++ [...
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:232
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1860
void setExternLoc(SourceLocation Loc)
Sets the location of the extern keyword.
static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS)
DeclarationName getName() const
getName - Returns the embedded declaration name.
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2944
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3175
void referenceDLLExportedClassMethods()
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc)
Build the type that describes a C++ typename specifier, e.g., "typename T::type". ...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration...
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:378
QualType getElementType() const
Definition: Type.h:2949
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:94
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3494
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
KindType getKind() const
Determine what kind of template argument we have.
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module *> *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:163
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isMemberPointer() const
Definition: APValue.h:192
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:54
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:360
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template...
static bool hasVisibleDefaultArgument(Sema &S, const ParmDecl *D, llvm::SmallVectorImpl< Module *> *Modules)
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1816
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:89
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
void setPointOfInstantiation(SourceLocation Loc)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:620
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2121
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2822
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
No entity found met the criteria.
Definition: Lookup.h:36
bool isLValue() const
Definition: APValue.h:187
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:161
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:146
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:301
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1780
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:174
EnumDecl * getDecl() const
Definition: Type.h:4009
A template type parameter, stored as a type.
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema&#39;s representation of template deduction information to the form used in overload-can...
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:562
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1462
void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We&#39;ve found a use of a template specialization that would select a partial specialization.
NamedDecl * next()
Definition: Lookup.h:646
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
bool isCanonical() const
Definition: Type.h:5762
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2214
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:586
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, Expr *AssociatedConstraints=nullptr)
Create a class template node.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:4633
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:2854
QualType getPointeeType() const
Definition: Type.h:2846
Represents a pack expansion of types.
Definition: Type.h:4994
SourceLocation getLocation() const
A POD class for pairing a NamedDecl* with an access specifier.
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1435
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1629
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
StringRef getName() const
Return the actual identifier string.
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<U>...
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1876
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:2415
Represents a template argument.
Definition: TemplateBase.h:51
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
TagTypeKind
The kind of a tag type.
Definition: Type.h:4686
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...
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
The name does not refer to a template.
Definition: TemplateKinds.h:23
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2455
void setMemberSpecialization()
Note that this member template is a specialization.
bool isNull() const
Determine whether this template name is NULL.
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we&#39;re in a current instantiation.
void removeDefaultArgument()
Removes the default argument of this template parameter.
Dataflow Directional Tag Classes.
bool isExplicit() const
Whether this function is explicit.
Definition: DeclCXX.h:2511
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
bool isValid() const
Return true if this is a valid SourceLocation object.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument&#39;s template name.
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:493
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2406
UnaryOperatorKind
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
NestedNameSpecifier * getQualifier() const
Definition: Type.h:4931
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1256
CanQualType NullPtrTy
Definition: ASTContext.h:1012
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:3496
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:224
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:466
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:130
SourceLocation getLocStart() const LLVM_READONLY
Definition: TypeLoc.h:154
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:80
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3430
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
CXXScopeSpec SS
The nested-name-specifier that precedes the template name.
bool isRecord() const
Definition: DeclBase.h:1409
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
Expr * getSourceExpression() const
Definition: TemplateBase.h:506
QualType getUnderlyingType() const
Definition: Decl.h:2853
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:116
AccessSpecifier getAccess() const
Definition: DeclBase.h:460
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:76
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:157
bool isInvalid() const
Determine whether the given template argument is invalid.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclarationName - The name of a declaration.
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:520
Expr * getDefaultArg()
Definition: Decl.cpp:2493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:979
Kind getKind() const
Definition: DeclBase.h:419
bool isBooleanType() const
Definition: Type.h:6232
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:3388
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:3652
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:1357
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:731
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
EnumDecl - Represents an enum.
Definition: Decl.h:3239
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2502
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:235
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:143
Expr * getDefaultArgument() const
Retrieve the default argument, if any.
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set...
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:574
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
A type that was preceded by the &#39;template&#39; keyword, stored as a Type*.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:340
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:629
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:238
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 &#39;auto&#39; typ...
Definition: Type.h:6238
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it&#39;s the object of a friend declaration...
Definition: DeclBase.h:1063
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2552
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1156
bool isMacroID() const
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getNumParams() const
Definition: TypeLoc.h:1471
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2084
Represents a pointer to an Objective C object.
Definition: Type.h:5440
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:150
Pointer to a block type.
Definition: Type.h:2385
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:45
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...
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed...
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:334
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:544
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3976
Complex values, per C99 6.2.5p11.
Definition: Type.h:2223
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:3771
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3447
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:6292
QualType getCanonicalTypeInternal() const
Definition: Type.h:2107
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:567
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:153
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos)
T * getAttr() const
Definition: DeclBase.h:531
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:1739
CanQualType DependentTy
Definition: ASTContext.h:1013
bool isFunctionType() const
Definition: Type.h:5938
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:713
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2444
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:707
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:66
ExtVectorType - Extended vector type.
Definition: Type.h:2988
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2419
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1663
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2190
Wrapper for source info for record types.
Definition: TypeLoc.h:717
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
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, AttributeList *Attr)
The template argument is a type.
Definition: TemplateBase.h:60
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
QualType getUnderlyingType() const
Definition: Type.h:3840
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:253
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:90
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1096
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1425
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:265
The template argument is actually a parameter pack.
Definition: TemplateBase.h:91
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2676
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2479
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this variable template specialization is actually an instantiation of the given variable te...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2007
This is a scope that can contain a declaration.
Definition: Scope.h:58
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1986
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2112
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2174
A template argument list.
Definition: DeclTemplate.h:210
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:239
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:406
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1378
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:235
unsigned getDepth() const
Definition: Type.h:4218
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
getCXXLiteralOperatorName - Get the name of the literal operator function with II as the identifier...
ValueKind getKind() const
Definition: APValue.h:181
TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false)
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:989
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5798
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization, returns the templated static data member from which it was instantiated.
Definition: Decl.cpp:2370
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4901
bool isValid() const
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:76
Represents a C array with an unspecified size.
Definition: Type.h:2672
TemplateName getCanonicalTemplateName(TemplateName Name) const
Retrieves the "canonical" template name that refers to a given template.
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member...
Definition: Decl.cpp:2140
void setConstexpr(bool IC)
Definition: Decl.h:2043
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5745
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1478
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:607
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:95
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1841
QualType getReplacementType() const
Gets the type that was substituted for the template parameter.
Definition: Type.h:4277
Location information for a TemplateArgument.
Definition: TemplateBase.h:393
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:328
The "enum" keyword.
Definition: Type.h:4700
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we&#39;ve not already done so.
Declaration of a class template.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1010
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool isVirtualSpecified() const
Definition: DeclSpec.h:566
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:127
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2143
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
iterator end() const
Definition: Lookup.h:339
A template-id, e.g., f<int>.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:265
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser&#39;s template argument list representation into our form.
Defines the clang::TargetInfo interface.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
SourceLocation getNameLoc() const
Definition: TypeLoc.h:518
bool isInlineSpecified() const
Definition: DeclSpec.h:559
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1645
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
ExprResult ExprError()
Definition: Ownership.h:267
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:930
CanQualType IntTy
Definition: ASTContext.h:1004
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization)
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:570
static Expr * formAssociatedConstraints(TemplateParameterList *Params, FunctionDecl *FD)
[temp.constr.decl]p2: A template&#39;s associated constraints are defined as a single constraint-expressi...
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1858
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:704
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:257
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
Represents an extended address space qualifier where the input address space value is dependent...
Definition: Type.h:2832
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4493
NamedDecl * getMostRecentDecl()
Definition: Decl.h:436
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2077
bool isPointerType() const
Definition: Type.h:5942
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3188
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:532
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Diagnose an arity mismatch in the.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, const TemplateArgumentListInfo &Args) const
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1126
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:586
QualType getType() const
Definition: Decl.h:638
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:111
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:342
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
Wrapper for template type parameters.
Definition: TypeLoc.h:733
A trivial tuple used to represent a source range.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:301
ASTContext & Context
Definition: Sema.h:316
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2845
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:530
bool isTranslationUnit() const
Definition: DeclBase.h:1405
void dropAttr()
Definition: DeclBase.h:506
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1068
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:75
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:455
A template template argument, stored as a template name.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2717
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters can be deduced from a given template argument list.
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1669
No keyword precedes the qualified type name.
Definition: Type.h:4726
APSInt & getInt()
Definition: APValue.h:201
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:281
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
iterator begin() const
Definition: Lookup.h:338
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:647
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:609
void setTypeAsWritten(TypeSourceInfo *T)
Sets the type of this specialization as it was written by the user.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:563
unsigned NumArgs
NumArgs - The number of template arguments.
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:527
The global specifier &#39;::&#39;. There is no stored value.
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
Definition: TemplateBase.h:288
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
void setType(QualType newType)
Definition: Decl.h:639
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:176
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:722
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2079
bool isDependent() const
Determines whether this is a dependent template name.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2618
Defines enum values for all the target-independent builtin functions.
Declaration of a template function.
Definition: DeclTemplate.h:967
void clear()
Clears out any current state.
Definition: Lookup.h:557
bool IsInsideALocalClassWithinATemplateFunction()
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2005
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
Attr - This represents one attribute.
Definition: Attr.h:43
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:738
SourceLocation getLocation() const
Definition: DeclBase.h:416
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1663
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
QualType getPointeeType() const
Definition: Type.h:2522
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:95
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1070
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:1073
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
getCXXOperatorName - Get the name of the overloadable C++ operator corresponding to Op...
A RAII object to temporarily push a declaration context.
Definition: Sema.h:705