clang  7.0.0svn
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