clang  6.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  if (TInfo->getType()->isUndeducedType()) {
934  diag::warn_cxx14_compat_template_nontype_parm_auto_type)
935  << QualType(TInfo->getType()->getContainedAutoType(), 0);
936  }
937 
938  assert(S->isTemplateParamScope() &&
939  "Non-type template parameter not in template parameter scope!");
940  bool Invalid = false;
941 
942  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
943  if (T.isNull()) {
944  T = Context.IntTy; // Recover with an 'int' type.
945  Invalid = true;
946  }
947 
948  IdentifierInfo *ParamName = D.getIdentifier();
949  bool IsParameterPack = D.hasEllipsis();
952  D.getLocStart(),
953  D.getIdentifierLoc(),
954  Depth, Position, ParamName, T,
955  IsParameterPack, TInfo);
956  Param->setAccess(AS_public);
957 
958  if (Invalid)
959  Param->setInvalidDecl();
960 
961  if (ParamName) {
963  ParamName);
964 
965  // Add the template parameter into the current scope.
966  S->AddDecl(Param);
967  IdResolver.AddDecl(Param);
968  }
969 
970  // C++0x [temp.param]p9:
971  // A default template-argument may be specified for any kind of
972  // template-parameter that is not a template parameter pack.
973  if (Default && IsParameterPack) {
974  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
975  Default = nullptr;
976  }
977 
978  // Check the well-formedness of the default template argument, if provided.
979  if (Default) {
980  // Check for unexpanded parameter packs.
981  if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
982  return Param;
983 
984  TemplateArgument Converted;
985  ExprResult DefaultRes =
986  CheckTemplateArgument(Param, Param->getType(), Default, Converted);
987  if (DefaultRes.isInvalid()) {
988  Param->setInvalidDecl();
989  return Param;
990  }
991  Default = DefaultRes.get();
992 
993  Param->setDefaultArgument(Default);
994  }
995 
996  return Param;
997 }
998 
999 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1000 /// parameter (e.g. T in template <template <typename> class T> class array)
1001 /// has been parsed. S is the current scope.
1003  SourceLocation TmpLoc,
1004  TemplateParameterList *Params,
1005  SourceLocation EllipsisLoc,
1006  IdentifierInfo *Name,
1007  SourceLocation NameLoc,
1008  unsigned Depth,
1009  unsigned Position,
1010  SourceLocation EqualLoc,
1011  ParsedTemplateArgument Default) {
1012  assert(S->isTemplateParamScope() &&
1013  "Template template parameter not in template parameter scope!");
1014 
1015  // Construct the parameter object.
1016  bool IsParameterPack = EllipsisLoc.isValid();
1017  TemplateTemplateParmDecl *Param =
1019  NameLoc.isInvalid()? TmpLoc : NameLoc,
1020  Depth, Position, IsParameterPack,
1021  Name, Params);
1022  Param->setAccess(AS_public);
1023 
1024  // If the template template parameter has a name, then link the identifier
1025  // into the scope and lookup mechanisms.
1026  if (Name) {
1027  maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1028 
1029  S->AddDecl(Param);
1030  IdResolver.AddDecl(Param);
1031  }
1032 
1033  if (Params->size() == 0) {
1034  Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1035  << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1036  Param->setInvalidDecl();
1037  }
1038 
1039  // C++0x [temp.param]p9:
1040  // A default template-argument may be specified for any kind of
1041  // template-parameter that is not a template parameter pack.
1042  if (IsParameterPack && !Default.isInvalid()) {
1043  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1044  Default = ParsedTemplateArgument();
1045  }
1046 
1047  if (!Default.isInvalid()) {
1048  // Check only that we have a template template argument. We don't want to
1049  // try to check well-formedness now, because our template template parameter
1050  // might have dependent types in its template parameters, which we wouldn't
1051  // be able to match now.
1052  //
1053  // If none of the template template parameter's template arguments mention
1054  // other template parameters, we could actually perform more checking here.
1055  // However, it isn't worth doing.
1056  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1057  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1058  Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1059  << DefaultArg.getSourceRange();
1060  return Param;
1061  }
1062 
1063  // Check for unexpanded parameter packs.
1064  if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1065  DefaultArg.getArgument().getAsTemplate(),
1066  UPPC_DefaultArgument))
1067  return Param;
1068 
1069  Param->setDefaultArgument(Context, DefaultArg);
1070  }
1071 
1072  return Param;
1073 }
1074 
1075 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1076 /// constrained by RequiresClause, that contains the template parameters in
1077 /// Params.
1080  SourceLocation ExportLoc,
1081  SourceLocation TemplateLoc,
1082  SourceLocation LAngleLoc,
1083  ArrayRef<NamedDecl *> Params,
1084  SourceLocation RAngleLoc,
1085  Expr *RequiresClause) {
1086  if (ExportLoc.isValid())
1087  Diag(ExportLoc, diag::warn_template_export_unsupported);
1088 
1090  Context, TemplateLoc, LAngleLoc,
1091  llvm::makeArrayRef(Params.data(), Params.size()),
1092  RAngleLoc, RequiresClause);
1093 }
1094 
1095 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1096  if (SS.isSet())
1098 }
1099 
1100 DeclResult
1101 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1102  SourceLocation KWLoc, CXXScopeSpec &SS,
1103  IdentifierInfo *Name, SourceLocation NameLoc,
1105  TemplateParameterList *TemplateParams,
1106  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1107  SourceLocation FriendLoc,
1108  unsigned NumOuterTemplateParamLists,
1109  TemplateParameterList** OuterTemplateParamLists,
1110  SkipBodyInfo *SkipBody) {
1111  assert(TemplateParams && TemplateParams->size() > 0 &&
1112  "No template parameters");
1113  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1114  bool Invalid = false;
1115 
1116  // Check that we can declare a template here.
1117  if (CheckTemplateDeclScope(S, TemplateParams))
1118  return true;
1119 
1121  assert(Kind != TTK_Enum && "can't build template of enumerated type");
1122 
1123  // There is no such thing as an unnamed class template.
1124  if (!Name) {
1125  Diag(KWLoc, diag::err_template_unnamed_class);
1126  return true;
1127  }
1128 
1129  // Find any previous declaration with this name. For a friend with no
1130  // scope explicitly specified, we only look for tag declarations (per
1131  // C++11 [basic.lookup.elab]p2).
1132  DeclContext *SemanticContext;
1133  LookupResult Previous(*this, Name, NameLoc,
1134  (SS.isEmpty() && TUK == TUK_Friend)
1135  ? LookupTagName : LookupOrdinaryName,
1136  forRedeclarationInCurContext());
1137  if (SS.isNotEmpty() && !SS.isInvalid()) {
1138  SemanticContext = computeDeclContext(SS, true);
1139  if (!SemanticContext) {
1140  // FIXME: Horrible, horrible hack! We can't currently represent this
1141  // in the AST, and historically we have just ignored such friend
1142  // class templates, so don't complain here.
1143  Diag(NameLoc, TUK == TUK_Friend
1144  ? diag::warn_template_qualified_friend_ignored
1145  : diag::err_template_qualified_declarator_no_match)
1146  << SS.getScopeRep() << SS.getRange();
1147  return TUK != TUK_Friend;
1148  }
1149 
1150  if (RequireCompleteDeclContext(SS, SemanticContext))
1151  return true;
1152 
1153  // If we're adding a template to a dependent context, we may need to
1154  // rebuilding some of the types used within the template parameter list,
1155  // now that we know what the current instantiation is.
1156  if (SemanticContext->isDependentContext()) {
1157  ContextRAII SavedContext(*this, SemanticContext);
1158  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1159  Invalid = true;
1160  } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1161  diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1162 
1163  LookupQualifiedName(Previous, SemanticContext);
1164  } else {
1165  SemanticContext = CurContext;
1166 
1167  // C++14 [class.mem]p14:
1168  // If T is the name of a class, then each of the following shall have a
1169  // name different from T:
1170  // -- every member template of class T
1171  if (TUK != TUK_Friend &&
1172  DiagnoseClassNameShadow(SemanticContext,
1173  DeclarationNameInfo(Name, NameLoc)))
1174  return true;
1175 
1176  LookupName(Previous, S);
1177  }
1178 
1179  if (Previous.isAmbiguous())
1180  return true;
1181 
1182  NamedDecl *PrevDecl = nullptr;
1183  if (Previous.begin() != Previous.end())
1184  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1185 
1186  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1187  // Maybe we will complain about the shadowed template parameter.
1188  DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1189  // Just pretend that we didn't see the previous declaration.
1190  PrevDecl = nullptr;
1191  }
1192 
1193  // If there is a previous declaration with the same name, check
1194  // whether this is a valid redeclaration.
1195  ClassTemplateDecl *PrevClassTemplate =
1196  dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1197 
1198  // We may have found the injected-class-name of a class template,
1199  // class template partial specialization, or class template specialization.
1200  // In these cases, grab the template that is being defined or specialized.
1201  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1202  cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1203  PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1204  PrevClassTemplate
1205  = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1206  if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1207  PrevClassTemplate
1208  = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1209  ->getSpecializedTemplate();
1210  }
1211  }
1212 
1213  if (TUK == TUK_Friend) {
1214  // C++ [namespace.memdef]p3:
1215  // [...] When looking for a prior declaration of a class or a function
1216  // declared as a friend, and when the name of the friend class or
1217  // function is neither a qualified name nor a template-id, scopes outside
1218  // the innermost enclosing namespace scope are not considered.
1219  if (!SS.isSet()) {
1220  DeclContext *OutermostContext = CurContext;
1221  while (!OutermostContext->isFileContext())
1222  OutermostContext = OutermostContext->getLookupParent();
1223 
1224  if (PrevDecl &&
1225  (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1226  OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1227  SemanticContext = PrevDecl->getDeclContext();
1228  } else {
1229  // Declarations in outer scopes don't matter. However, the outermost
1230  // context we computed is the semantic context for our new
1231  // declaration.
1232  PrevDecl = PrevClassTemplate = nullptr;
1233  SemanticContext = OutermostContext;
1234 
1235  // Check that the chosen semantic context doesn't already contain a
1236  // declaration of this name as a non-tag type.
1237  Previous.clear(LookupOrdinaryName);
1238  DeclContext *LookupContext = SemanticContext;
1239  while (LookupContext->isTransparentContext())
1240  LookupContext = LookupContext->getLookupParent();
1241  LookupQualifiedName(Previous, LookupContext);
1242 
1243  if (Previous.isAmbiguous())
1244  return true;
1245 
1246  if (Previous.begin() != Previous.end())
1247  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1248  }
1249  }
1250  } else if (PrevDecl &&
1251  !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1252  S, SS.isValid()))
1253  PrevDecl = PrevClassTemplate = nullptr;
1254 
1255  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1256  PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1257  if (SS.isEmpty() &&
1258  !(PrevClassTemplate &&
1259  PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1260  SemanticContext->getRedeclContext()))) {
1261  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1262  Diag(Shadow->getTargetDecl()->getLocation(),
1263  diag::note_using_decl_target);
1264  Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1265  // Recover by ignoring the old declaration.
1266  PrevDecl = PrevClassTemplate = nullptr;
1267  }
1268  }
1269 
1270  // TODO Memory management; associated constraints are not always stored.
1271  Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1272 
1273  if (PrevClassTemplate) {
1274  // Ensure that the template parameter lists are compatible. Skip this check
1275  // for a friend in a dependent context: the template parameter list itself
1276  // could be dependent.
1277  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1278  !TemplateParameterListsAreEqual(TemplateParams,
1279  PrevClassTemplate->getTemplateParameters(),
1280  /*Complain=*/true,
1281  TPL_TemplateMatch))
1282  return true;
1283 
1284  // Check for matching associated constraints on redeclarations.
1285  const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1286  const bool RedeclACMismatch = [&] {
1287  if (!(CurAC || PrevAC))
1288  return false; // Nothing to check; no mismatch.
1289  if (CurAC && PrevAC) {
1290  llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1291  CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1292  PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1293  if (CurACInfo == PrevACInfo)
1294  return false; // All good; no mismatch.
1295  }
1296  return true;
1297  }();
1298 
1299  if (RedeclACMismatch) {
1300  Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1301  diag::err_template_different_associated_constraints);
1302  Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1303  diag::note_template_prev_declaration) << /*declaration*/0;
1304  return true;
1305  }
1306 
1307  // C++ [temp.class]p4:
1308  // In a redeclaration, partial specialization, explicit
1309  // specialization or explicit instantiation of a class template,
1310  // the class-key shall agree in kind with the original class
1311  // template declaration (7.1.5.3).
1312  RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1313  if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1314  TUK == TUK_Definition, KWLoc, Name)) {
1315  Diag(KWLoc, diag::err_use_with_wrong_tag)
1316  << Name
1317  << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1318  Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1319  Kind = PrevRecordDecl->getTagKind();
1320  }
1321 
1322  // Check for redefinition of this class template.
1323  if (TUK == TUK_Definition) {
1324  if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1325  // If we have a prior definition that is not visible, treat this as
1326  // simply making that previous definition visible.
1327  NamedDecl *Hidden = nullptr;
1328  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1329  SkipBody->ShouldSkip = true;
1330  auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1331  assert(Tmpl && "original definition of a class template is not a "
1332  "class template?");
1333  makeMergedDefinitionVisible(Hidden);
1334  makeMergedDefinitionVisible(Tmpl);
1335  return Def;
1336  }
1337 
1338  Diag(NameLoc, diag::err_redefinition) << Name;
1339  Diag(Def->getLocation(), diag::note_previous_definition);
1340  // FIXME: Would it make sense to try to "forget" the previous
1341  // definition, as part of error recovery?
1342  return true;
1343  }
1344  }
1345  } else if (PrevDecl) {
1346  // C++ [temp]p5:
1347  // A class template shall not have the same name as any other
1348  // template, class, function, object, enumeration, enumerator,
1349  // namespace, or type in the same scope (3.3), except as specified
1350  // in (14.5.4).
1351  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1352  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1353  return true;
1354  }
1355 
1356  // Check the template parameter list of this declaration, possibly
1357  // merging in the template parameter list from the previous class
1358  // template declaration. Skip this check for a friend in a dependent
1359  // context, because the template parameter list might be dependent.
1360  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1361  CheckTemplateParameterList(
1362  TemplateParams,
1363  PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1364  : nullptr,
1365  (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1366  SemanticContext->isDependentContext())
1367  ? TPC_ClassTemplateMember
1368  : TUK == TUK_Friend ? TPC_FriendClassTemplate
1369  : TPC_ClassTemplate))
1370  Invalid = true;
1371 
1372  if (SS.isSet()) {
1373  // If the name of the template was qualified, we must be defining the
1374  // template out-of-line.
1375  if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1376  Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1377  : diag::err_member_decl_does_not_match)
1378  << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1379  Invalid = true;
1380  }
1381  }
1382 
1383  // If this is a templated friend in a dependent context we should not put it
1384  // on the redecl chain. In some cases, the templated friend can be the most
1385  // recent declaration tricking the template instantiator to make substitutions
1386  // there.
1387  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1388  bool ShouldAddRedecl
1389  = !(TUK == TUK_Friend && CurContext->isDependentContext());
1390 
1391  CXXRecordDecl *NewClass =
1392  CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1393  PrevClassTemplate && ShouldAddRedecl ?
1394  PrevClassTemplate->getTemplatedDecl() : nullptr,
1395  /*DelayTypeCreation=*/true);
1396  SetNestedNameSpecifier(NewClass, SS);
1397  if (NumOuterTemplateParamLists > 0)
1399  Context, llvm::makeArrayRef(OuterTemplateParamLists,
1400  NumOuterTemplateParamLists));
1401 
1402  // Add alignment attributes if necessary; these attributes are checked when
1403  // the ASTContext lays out the structure.
1404  if (TUK == TUK_Definition) {
1405  AddAlignmentAttributesForRecord(NewClass);
1406  AddMsStructLayoutForRecord(NewClass);
1407  }
1408 
1409  // Attach the associated constraints when the declaration will not be part of
1410  // a decl chain.
1411  Expr *const ACtoAttach =
1412  PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1413 
1414  ClassTemplateDecl *NewTemplate
1415  = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1416  DeclarationName(Name), TemplateParams,
1417  NewClass, ACtoAttach);
1418 
1419  if (ShouldAddRedecl)
1420  NewTemplate->setPreviousDecl(PrevClassTemplate);
1421 
1422  NewClass->setDescribedClassTemplate(NewTemplate);
1423 
1424  if (ModulePrivateLoc.isValid())
1425  NewTemplate->setModulePrivate();
1426 
1427  // Build the type for the class template declaration now.
1429  T = Context.getInjectedClassNameType(NewClass, T);
1430  assert(T->isDependentType() && "Class template type is not dependent?");
1431  (void)T;
1432 
1433  // If we are providing an explicit specialization of a member that is a
1434  // class template, make a note of that.
1435  if (PrevClassTemplate &&
1436  PrevClassTemplate->getInstantiatedFromMemberTemplate())
1437  PrevClassTemplate->setMemberSpecialization();
1438 
1439  // Set the access specifier.
1440  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1441  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1442 
1443  // Set the lexical context of these templates
1444  NewClass->setLexicalDeclContext(CurContext);
1445  NewTemplate->setLexicalDeclContext(CurContext);
1446 
1447  if (TUK == TUK_Definition)
1448  NewClass->startDefinition();
1449 
1450  if (Attr)
1451  ProcessDeclAttributeList(S, NewClass, Attr);
1452 
1453  if (PrevClassTemplate)
1454  mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1455 
1456  AddPushedVisibilityAttribute(NewClass);
1457 
1458  if (TUK != TUK_Friend) {
1459  // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1460  Scope *Outer = S;
1461  while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1462  Outer = Outer->getParent();
1463  PushOnScopeChains(NewTemplate, Outer);
1464  } else {
1465  if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1466  NewTemplate->setAccess(PrevClassTemplate->getAccess());
1467  NewClass->setAccess(PrevClassTemplate->getAccess());
1468  }
1469 
1470  NewTemplate->setObjectOfFriendDecl();
1471 
1472  // Friend templates are visible in fairly strange ways.
1473  if (!CurContext->isDependentContext()) {
1474  DeclContext *DC = SemanticContext->getRedeclContext();
1475  DC->makeDeclVisibleInContext(NewTemplate);
1476  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1477  PushOnScopeChains(NewTemplate, EnclosingScope,
1478  /* AddToContext = */ false);
1479  }
1480 
1481  FriendDecl *Friend = FriendDecl::Create(
1482  Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1483  Friend->setAccess(AS_public);
1484  CurContext->addDecl(Friend);
1485  }
1486 
1487  if (PrevClassTemplate)
1488  CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1489 
1490  if (Invalid) {
1491  NewTemplate->setInvalidDecl();
1492  NewClass->setInvalidDecl();
1493  }
1494 
1495  ActOnDocumentableDecl(NewTemplate);
1496 
1497  return NewTemplate;
1498 }
1499 
1500 namespace {
1501 /// Transform to convert portions of a constructor declaration into the
1502 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1503 struct ConvertConstructorToDeductionGuideTransform {
1504  ConvertConstructorToDeductionGuideTransform(Sema &S,
1505  ClassTemplateDecl *Template)
1506  : SemaRef(S), Template(Template) {}
1507 
1508  Sema &SemaRef;
1509  ClassTemplateDecl *Template;
1510 
1511  DeclContext *DC = Template->getDeclContext();
1512  CXXRecordDecl *Primary = Template->getTemplatedDecl();
1513  DeclarationName DeductionGuideName =
1515 
1516  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1517 
1518  // Index adjustment to apply to convert depth-1 template parameters into
1519  // depth-0 template parameters.
1520  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1521 
1522  /// Transform a constructor declaration into a deduction guide.
1523  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1524  CXXConstructorDecl *CD) {
1526 
1527  LocalInstantiationScope Scope(SemaRef);
1528 
1529  // C++ [over.match.class.deduct]p1:
1530  // -- For each constructor of the class template designated by the
1531  // template-name, a function template with the following properties:
1532 
1533  // -- The template parameters are the template parameters of the class
1534  // template followed by the template parameters (including default
1535  // template arguments) of the constructor, if any.
1536  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1537  if (FTD) {
1538  TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1539  SmallVector<NamedDecl *, 16> AllParams;
1540  AllParams.reserve(TemplateParams->size() + InnerParams->size());
1541  AllParams.insert(AllParams.begin(),
1542  TemplateParams->begin(), TemplateParams->end());
1543  SubstArgs.reserve(InnerParams->size());
1544 
1545  // Later template parameters could refer to earlier ones, so build up
1546  // a list of substituted template arguments as we go.
1547  for (NamedDecl *Param : *InnerParams) {
1549  Args.addOuterTemplateArguments(SubstArgs);
1550  Args.addOuterRetainedLevel();
1551  NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1552  if (!NewParam)
1553  return nullptr;
1554  AllParams.push_back(NewParam);
1555  SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1556  SemaRef.Context.getInjectedTemplateArg(NewParam)));
1557  }
1558  TemplateParams = TemplateParameterList::Create(
1559  SemaRef.Context, InnerParams->getTemplateLoc(),
1560  InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1561  /*FIXME: RequiresClause*/ nullptr);
1562  }
1563 
1564  // If we built a new template-parameter-list, track that we need to
1565  // substitute references to the old parameters into references to the
1566  // new ones.
1568  if (FTD) {
1569  Args.addOuterTemplateArguments(SubstArgs);
1570  Args.addOuterRetainedLevel();
1571  }
1572 
1575  assert(FPTL && "no prototype for constructor declaration");
1576 
1577  // Transform the type of the function, adjusting the return type and
1578  // replacing references to the old parameters with references to the
1579  // new ones.
1580  TypeLocBuilder TLB;
1582  QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1583  if (NewType.isNull())
1584  return nullptr;
1585  TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1586 
1587  return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1588  CD->getLocStart(), CD->getLocation(),
1589  CD->getLocEnd());
1590  }
1591 
1592  /// Build a deduction guide with the specified parameter types.
1593  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1594  SourceLocation Loc = Template->getLocation();
1595 
1596  // Build the requested type.
1598  EPI.HasTrailingReturn = true;
1599  QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1600  DeductionGuideName, EPI);
1601  TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1602 
1603  FunctionProtoTypeLoc FPTL =
1605 
1606  // Build the parameters, needed during deduction / substitution.
1608  for (auto T : ParamTypes) {
1609  ParmVarDecl *NewParam = ParmVarDecl::Create(
1610  SemaRef.Context, DC, Loc, Loc, nullptr, T,
1611  SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1612  NewParam->setScopeInfo(0, Params.size());
1613  FPTL.setParam(Params.size(), NewParam);
1614  Params.push_back(NewParam);
1615  }
1616 
1617  return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1618  Loc, Loc, Loc);
1619  }
1620 
1621 private:
1622  /// Transform a constructor template parameter into a deduction guide template
1623  /// parameter, rebuilding any internal references to earlier parameters and
1624  /// renumbering as we go.
1625  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1627  if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1628  // TemplateTypeParmDecl's index cannot be changed after creation, so
1629  // substitute it directly.
1630  auto *NewTTP = TemplateTypeParmDecl::Create(
1631  SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1632  /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1633  TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1634  TTP->isParameterPack());
1635  if (TTP->hasDefaultArgument()) {
1636  TypeSourceInfo *InstantiatedDefaultArg =
1637  SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1638  TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1639  if (InstantiatedDefaultArg)
1640  NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1641  }
1642  SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1643  NewTTP);
1644  return NewTTP;
1645  }
1646 
1647  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1648  return transformTemplateParameterImpl(TTP, Args);
1649 
1650  return transformTemplateParameterImpl(
1651  cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1652  }
1653  template<typename TemplateParmDecl>
1654  TemplateParmDecl *
1655  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1657  // Ask the template instantiator to do the heavy lifting for us, then adjust
1658  // the index of the parameter once it's done.
1659  auto *NewParam =
1660  cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1661  assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1662  NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1663  return NewParam;
1664  }
1665 
1666  QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1670  SmallVector<QualType, 4> ParamTypes;
1671  const FunctionProtoType *T = TL.getTypePtr();
1672 
1673  // -- The types of the function parameters are those of the constructor.
1674  for (auto *OldParam : TL.getParams()) {
1675  ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1676  if (!NewParam)
1677  return QualType();
1678  ParamTypes.push_back(NewParam->getType());
1679  Params.push_back(NewParam);
1680  }
1681 
1682  // -- The return type is the class template specialization designated by
1683  // the template-name and template arguments corresponding to the
1684  // template parameters obtained from the class template.
1685  //
1686  // We use the injected-class-name type of the primary template instead.
1687  // This has the convenient property that it is different from any type that
1688  // the user can write in a deduction-guide (because they cannot enter the
1689  // context of the template), so implicit deduction guides can never collide
1690  // with explicit ones.
1691  QualType ReturnType = DeducedType;
1692  TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1693 
1694  // Resolving a wording defect, we also inherit the variadicness of the
1695  // constructor.
1697  EPI.Variadic = T->isVariadic();
1698  EPI.HasTrailingReturn = true;
1699 
1700  QualType Result = SemaRef.BuildFunctionType(
1701  ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1702  if (Result.isNull())
1703  return QualType();
1704 
1705  FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1707  NewTL.setLParenLoc(TL.getLParenLoc());
1708  NewTL.setRParenLoc(TL.getRParenLoc());
1710  NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1711  for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1712  NewTL.setParam(I, Params[I]);
1713 
1714  return Result;
1715  }
1716 
1717  ParmVarDecl *
1718  transformFunctionTypeParam(ParmVarDecl *OldParam,
1720  TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1721  TypeSourceInfo *NewDI;
1722  if (!Args.getNumLevels())
1723  NewDI = OldDI;
1724  else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1725  // Expand out the one and only element in each inner pack.
1726  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1727  NewDI =
1728  SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1729  OldParam->getLocation(), OldParam->getDeclName());
1730  if (!NewDI) return nullptr;
1731  NewDI =
1732  SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1733  PackTL.getTypePtr()->getNumExpansions());
1734  } else
1735  NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1736  OldParam->getDeclName());
1737  if (!NewDI)
1738  return nullptr;
1739 
1740  // Canonicalize the type. This (for instance) replaces references to
1741  // typedef members of the current instantiations with the definitions of
1742  // those typedefs, avoiding triggering instantiation of the deduced type
1743  // during deduction.
1744  // FIXME: It would be preferable to retain type sugar and source
1745  // information here (and handle this in substitution instead).
1746  NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1747  SemaRef.Context.getCanonicalType(NewDI->getType()),
1748  OldParam->getLocation());
1749 
1750  // Resolving a wording defect, we also inherit default arguments from the
1751  // constructor.
1752  ExprResult NewDefArg;
1753  if (OldParam->hasDefaultArg()) {
1754  NewDefArg = Args.getNumLevels()
1755  ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1756  : OldParam->getDefaultArg();
1757  if (NewDefArg.isInvalid())
1758  return nullptr;
1759  }
1760 
1761  ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1762  OldParam->getInnerLocStart(),
1763  OldParam->getLocation(),
1764  OldParam->getIdentifier(),
1765  NewDI->getType(),
1766  NewDI,
1767  OldParam->getStorageClass(),
1768  NewDefArg.get());
1769  NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1770  OldParam->getFunctionScopeIndex());
1771  return NewParam;
1772  }
1773 
1774  NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1775  bool Explicit, TypeSourceInfo *TInfo,
1776  SourceLocation LocStart, SourceLocation Loc,
1777  SourceLocation LocEnd) {
1778  DeclarationNameInfo Name(DeductionGuideName, Loc);
1779  ArrayRef<ParmVarDecl *> Params =
1780  TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1781 
1782  // Build the implicit deduction guide template.
1783  auto *Guide =
1784  CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1785  Name, TInfo->getType(), TInfo, LocEnd);
1786  Guide->setImplicit();
1787  Guide->setParams(Params);
1788 
1789  for (auto *Param : Params)
1790  Param->setDeclContext(Guide);
1791 
1792  auto *GuideTemplate = FunctionTemplateDecl::Create(
1793  SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1794  GuideTemplate->setImplicit();
1795  Guide->setDescribedFunctionTemplate(GuideTemplate);
1796 
1797  if (isa<CXXRecordDecl>(DC)) {
1798  Guide->setAccess(AS_public);
1799  GuideTemplate->setAccess(AS_public);
1800  }
1801 
1802  DC->addDecl(GuideTemplate);
1803  return GuideTemplate;
1804  }
1805 };
1806 }
1807 
1809  SourceLocation Loc) {
1810  DeclContext *DC = Template->getDeclContext();
1811  if (DC->isDependentContext())
1812  return;
1813 
1814  ConvertConstructorToDeductionGuideTransform Transform(
1815  *this, cast<ClassTemplateDecl>(Template));
1816  if (!isCompleteType(Loc, Transform.DeducedType))
1817  return;
1818 
1819  // Check whether we've already declared deduction guides for this template.
1820  // FIXME: Consider storing a flag on the template to indicate this.
1821  auto Existing = DC->lookup(Transform.DeductionGuideName);
1822  for (auto *D : Existing)
1823  if (D->isImplicit())
1824  return;
1825 
1826  // In case we were expanding a pack when we attempted to declare deduction
1827  // guides, turn off pack expansion for everything we're about to do.
1828  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1829  // Create a template instantiation record to track the "instantiation" of
1830  // constructors into deduction guides.
1831  // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1832  // this substitution process actually fail?
1833  InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1834 
1835  // Convert declared constructors into deduction guide templates.
1836  // FIXME: Skip constructors for which deduction must necessarily fail (those
1837  // for which some class template parameter without a default argument never
1838  // appears in a deduced context).
1839  bool AddedAny = false;
1840  for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1841  D = D->getUnderlyingDecl();
1842  if (D->isInvalidDecl() || D->isImplicit())
1843  continue;
1844  D = cast<NamedDecl>(D->getCanonicalDecl());
1845 
1846  auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1847  auto *CD =
1848  dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1849  // Class-scope explicit specializations (MS extension) do not result in
1850  // deduction guides.
1851  if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1852  continue;
1853 
1854  Transform.transformConstructor(FTD, CD);
1855  AddedAny = true;
1856  }
1857 
1858  // C++17 [over.match.class.deduct]
1859  // -- If C is not defined or does not declare any constructors, an
1860  // additional function template derived as above from a hypothetical
1861  // constructor C().
1862  if (!AddedAny)
1863  Transform.buildSimpleDeductionGuide(None);
1864 
1865  // -- An additional function template derived as above from a hypothetical
1866  // constructor C(C), called the copy deduction candidate.
1867  cast<CXXDeductionGuideDecl>(
1868  cast<FunctionTemplateDecl>(
1869  Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1870  ->getTemplatedDecl())
1871  ->setIsCopyDeductionCandidate();
1872 }
1873 
1874 /// \brief Diagnose the presence of a default template argument on a
1875 /// template parameter, which is ill-formed in certain contexts.
1876 ///
1877 /// \returns true if the default template argument should be dropped.
1880  SourceLocation ParamLoc,
1881  SourceRange DefArgRange) {
1882  switch (TPC) {
1884  case Sema::TPC_VarTemplate:
1886  return false;
1887 
1890  // C++ [temp.param]p9:
1891  // A default template-argument shall not be specified in a
1892  // function template declaration or a function template
1893  // definition [...]
1894  // If a friend function template declaration specifies a default
1895  // template-argument, that declaration shall be a definition and shall be
1896  // the only declaration of the function template in the translation unit.
1897  // (C++98/03 doesn't have this wording; see DR226).
1898  S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1899  diag::warn_cxx98_compat_template_parameter_default_in_function_template
1900  : diag::ext_template_parameter_default_in_function_template)
1901  << DefArgRange;
1902  return false;
1903 
1905  // C++0x [temp.param]p9:
1906  // A default template-argument shall not be specified in the
1907  // template-parameter-lists of the definition of a member of a
1908  // class template that appears outside of the member's class.
1909  S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1910  << DefArgRange;
1911  return true;
1912 
1915  // C++ [temp.param]p9:
1916  // A default template-argument shall not be specified in a
1917  // friend template declaration.
1918  S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1919  << DefArgRange;
1920  return true;
1921 
1922  // FIXME: C++0x [temp.param]p9 allows default template-arguments
1923  // for friend function templates if there is only a single
1924  // declaration (and it is a definition). Strange!
1925  }
1926 
1927  llvm_unreachable("Invalid TemplateParamListContext!");
1928 }
1929 
1930 /// \brief Check for unexpanded parameter packs within the template parameters
1931 /// of a template template parameter, recursively.
1933  TemplateTemplateParmDecl *TTP) {
1934  // A template template parameter which is a parameter pack is also a pack
1935  // expansion.
1936  if (TTP->isParameterPack())
1937  return false;
1938 
1940  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1941  NamedDecl *P = Params->getParam(I);
1942  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1943  if (!NTTP->isParameterPack() &&
1944  S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1945  NTTP->getTypeSourceInfo(),
1947  return true;
1948 
1949  continue;
1950  }
1951 
1952  if (TemplateTemplateParmDecl *InnerTTP
1953  = dyn_cast<TemplateTemplateParmDecl>(P))
1954  if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1955  return true;
1956  }
1957 
1958  return false;
1959 }
1960 
1961 /// \brief Checks the validity of a template parameter list, possibly
1962 /// considering the template parameter list from a previous
1963 /// declaration.
1964 ///
1965 /// If an "old" template parameter list is provided, it must be
1966 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1967 /// template parameter list.
1968 ///
1969 /// \param NewParams Template parameter list for a new template
1970 /// declaration. This template parameter list will be updated with any
1971 /// default arguments that are carried through from the previous
1972 /// template parameter list.
1973 ///
1974 /// \param OldParams If provided, template parameter list from a
1975 /// previous declaration of the same template. Default template
1976 /// arguments will be merged from the old template parameter list to
1977 /// the new template parameter list.
1978 ///
1979 /// \param TPC Describes the context in which we are checking the given
1980 /// template parameter list.
1981 ///
1982 /// \returns true if an error occurred, false otherwise.
1984  TemplateParameterList *OldParams,
1986  bool Invalid = false;
1987 
1988  // C++ [temp.param]p10:
1989  // The set of default template-arguments available for use with a
1990  // template declaration or definition is obtained by merging the
1991  // default arguments from the definition (if in scope) and all
1992  // declarations in scope in the same way default function
1993  // arguments are (8.3.6).
1994  bool SawDefaultArgument = false;
1995  SourceLocation PreviousDefaultArgLoc;
1996 
1997  // Dummy initialization to avoid warnings.
1998  TemplateParameterList::iterator OldParam = NewParams->end();
1999  if (OldParams)
2000  OldParam = OldParams->begin();
2001 
2002  bool RemoveDefaultArguments = false;
2003  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2004  NewParamEnd = NewParams->end();
2005  NewParam != NewParamEnd; ++NewParam) {
2006  // Variables used to diagnose redundant default arguments
2007  bool RedundantDefaultArg = false;
2008  SourceLocation OldDefaultLoc;
2009  SourceLocation NewDefaultLoc;
2010 
2011  // Variable used to diagnose missing default arguments
2012  bool MissingDefaultArg = false;
2013 
2014  // Variable used to diagnose non-final parameter packs
2015  bool SawParameterPack = false;
2016 
2017  if (TemplateTypeParmDecl *NewTypeParm
2018  = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2019  // Check the presence of a default argument here.
2020  if (NewTypeParm->hasDefaultArgument() &&
2022  NewTypeParm->getLocation(),
2023  NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2024  .getSourceRange()))
2025  NewTypeParm->removeDefaultArgument();
2026 
2027  // Merge default arguments for template type parameters.
2028  TemplateTypeParmDecl *OldTypeParm
2029  = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2030  if (NewTypeParm->isParameterPack()) {
2031  assert(!NewTypeParm->hasDefaultArgument() &&
2032  "Parameter packs can't have a default argument!");
2033  SawParameterPack = true;
2034  } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2035  NewTypeParm->hasDefaultArgument()) {
2036  OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2037  NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2038  SawDefaultArgument = true;
2039  RedundantDefaultArg = true;
2040  PreviousDefaultArgLoc = NewDefaultLoc;
2041  } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2042  // Merge the default argument from the old declaration to the
2043  // new declaration.
2044  NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2045  PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2046  } else if (NewTypeParm->hasDefaultArgument()) {
2047  SawDefaultArgument = true;
2048  PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2049  } else if (SawDefaultArgument)
2050  MissingDefaultArg = true;
2051  } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2052  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2053  // Check for unexpanded parameter packs.
2054  if (!NewNonTypeParm->isParameterPack() &&
2055  DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2056  NewNonTypeParm->getTypeSourceInfo(),
2057  UPPC_NonTypeTemplateParameterType)) {
2058  Invalid = true;
2059  continue;
2060  }
2061 
2062  // Check the presence of a default argument here.
2063  if (NewNonTypeParm->hasDefaultArgument() &&
2065  NewNonTypeParm->getLocation(),
2066  NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2067  NewNonTypeParm->removeDefaultArgument();
2068  }
2069 
2070  // Merge default arguments for non-type template parameters
2071  NonTypeTemplateParmDecl *OldNonTypeParm
2072  = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2073  if (NewNonTypeParm->isParameterPack()) {
2074  assert(!NewNonTypeParm->hasDefaultArgument() &&
2075  "Parameter packs can't have a default argument!");
2076  if (!NewNonTypeParm->isPackExpansion())
2077  SawParameterPack = true;
2078  } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2079  NewNonTypeParm->hasDefaultArgument()) {
2080  OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2081  NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2082  SawDefaultArgument = true;
2083  RedundantDefaultArg = true;
2084  PreviousDefaultArgLoc = NewDefaultLoc;
2085  } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2086  // Merge the default argument from the old declaration to the
2087  // new declaration.
2088  NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2089  PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2090  } else if (NewNonTypeParm->hasDefaultArgument()) {
2091  SawDefaultArgument = true;
2092  PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2093  } else if (SawDefaultArgument)
2094  MissingDefaultArg = true;
2095  } else {
2096  TemplateTemplateParmDecl *NewTemplateParm
2097  = cast<TemplateTemplateParmDecl>(*NewParam);
2098 
2099  // Check for unexpanded parameter packs, recursively.
2100  if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2101  Invalid = true;
2102  continue;
2103  }
2104 
2105  // Check the presence of a default argument here.
2106  if (NewTemplateParm->hasDefaultArgument() &&
2108  NewTemplateParm->getLocation(),
2109  NewTemplateParm->getDefaultArgument().getSourceRange()))
2110  NewTemplateParm->removeDefaultArgument();
2111 
2112  // Merge default arguments for template template parameters
2113  TemplateTemplateParmDecl *OldTemplateParm
2114  = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2115  if (NewTemplateParm->isParameterPack()) {
2116  assert(!NewTemplateParm->hasDefaultArgument() &&
2117  "Parameter packs can't have a default argument!");
2118  if (!NewTemplateParm->isPackExpansion())
2119  SawParameterPack = true;
2120  } else if (OldTemplateParm &&
2121  hasVisibleDefaultArgument(OldTemplateParm) &&
2122  NewTemplateParm->hasDefaultArgument()) {
2123  OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2124  NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2125  SawDefaultArgument = true;
2126  RedundantDefaultArg = true;
2127  PreviousDefaultArgLoc = NewDefaultLoc;
2128  } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2129  // Merge the default argument from the old declaration to the
2130  // new declaration.
2131  NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2132  PreviousDefaultArgLoc
2133  = OldTemplateParm->getDefaultArgument().getLocation();
2134  } else if (NewTemplateParm->hasDefaultArgument()) {
2135  SawDefaultArgument = true;
2136  PreviousDefaultArgLoc
2137  = NewTemplateParm->getDefaultArgument().getLocation();
2138  } else if (SawDefaultArgument)
2139  MissingDefaultArg = true;
2140  }
2141 
2142  // C++11 [temp.param]p11:
2143  // If a template parameter of a primary class template or alias template
2144  // is a template parameter pack, it shall be the last template parameter.
2145  if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2146  (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2147  TPC == TPC_TypeAliasTemplate)) {
2148  Diag((*NewParam)->getLocation(),
2149  diag::err_template_param_pack_must_be_last_template_parameter);
2150  Invalid = true;
2151  }
2152 
2153  if (RedundantDefaultArg) {
2154  // C++ [temp.param]p12:
2155  // A template-parameter shall not be given default arguments
2156  // by two different declarations in the same scope.
2157  Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2158  Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2159  Invalid = true;
2160  } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2161  // C++ [temp.param]p11:
2162  // If a template-parameter of a class template has a default
2163  // template-argument, each subsequent template-parameter shall either
2164  // have a default template-argument supplied or be a template parameter
2165  // pack.
2166  Diag((*NewParam)->getLocation(),
2167  diag::err_template_param_default_arg_missing);
2168  Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2169  Invalid = true;
2170  RemoveDefaultArguments = true;
2171  }
2172 
2173  // If we have an old template parameter list that we're merging
2174  // in, move on to the next parameter.
2175  if (OldParams)
2176  ++OldParam;
2177  }
2178 
2179  // We were missing some default arguments at the end of the list, so remove
2180  // all of the default arguments.
2181  if (RemoveDefaultArguments) {
2182  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2183  NewParamEnd = NewParams->end();
2184  NewParam != NewParamEnd; ++NewParam) {
2185  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2186  TTP->removeDefaultArgument();
2187  else if (NonTypeTemplateParmDecl *NTTP
2188  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2189  NTTP->removeDefaultArgument();
2190  else
2191  cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2192  }
2193  }
2194 
2195  return Invalid;
2196 }
2197 
2198 namespace {
2199 
2200 /// A class which looks for a use of a certain level of template
2201 /// parameter.
2202 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2204 
2205  unsigned Depth;
2206 
2207  // Whether we're looking for a use of a template parameter that makes the
2208  // overall construct type-dependent / a dependent type. This is strictly
2209  // best-effort for now; we may fail to match at all for a dependent type
2210  // in some cases if this is set.
2211  bool IgnoreNonTypeDependent;
2212 
2213  bool Match;
2214  SourceLocation MatchLoc;
2215 
2216  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2217  : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2218  Match(false) {}
2219 
2220  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2221  : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2222  NamedDecl *ND = Params->getParam(0);
2223  if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2224  Depth = PD->getDepth();
2225  } else if (NonTypeTemplateParmDecl *PD =
2226  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2227  Depth = PD->getDepth();
2228  } else {
2229  Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2230  }
2231  }
2232 
2233  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2234  if (ParmDepth >= Depth) {
2235  Match = true;
2236  MatchLoc = Loc;
2237  return true;
2238  }
2239  return false;
2240  }
2241 
2242  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2243  // Prune out non-type-dependent expressions if requested. This can
2244  // sometimes result in us failing to find a template parameter reference
2245  // (if a value-dependent expression creates a dependent type), but this
2246  // mode is best-effort only.
2247  if (auto *E = dyn_cast_or_null<Expr>(S))
2248  if (IgnoreNonTypeDependent && !E->isTypeDependent())
2249  return true;
2250  return super::TraverseStmt(S, Q);
2251  }
2252 
2253  bool TraverseTypeLoc(TypeLoc TL) {
2254  if (IgnoreNonTypeDependent && !TL.isNull() &&
2255  !TL.getType()->isDependentType())
2256  return true;
2257  return super::TraverseTypeLoc(TL);
2258  }
2259 
2260  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2261  return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2262  }
2263 
2264  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2265  // For a best-effort search, keep looking until we find a location.
2266  return IgnoreNonTypeDependent || !Matches(T->getDepth());
2267  }
2268 
2269  bool TraverseTemplateName(TemplateName N) {
2270  if (TemplateTemplateParmDecl *PD =
2271  dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2272  if (Matches(PD->getDepth()))
2273  return false;
2274  return super::TraverseTemplateName(N);
2275  }
2276 
2277  bool VisitDeclRefExpr(DeclRefExpr *E) {
2278  if (NonTypeTemplateParmDecl *PD =
2279  dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2280  if (Matches(PD->getDepth(), E->getExprLoc()))
2281  return false;
2282  return super::VisitDeclRefExpr(E);
2283  }
2284 
2285  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2286  return TraverseType(T->getReplacementType());
2287  }
2288 
2289  bool
2290  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2291  return TraverseTemplateArgument(T->getArgumentPack());
2292  }
2293 
2294  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2295  return TraverseType(T->getInjectedSpecializationType());
2296  }
2297 };
2298 } // end anonymous namespace
2299 
2300 /// Determines whether a given type depends on the given parameter
2301 /// list.
2302 static bool
2304  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2305  Checker.TraverseType(T);
2306  return Checker.Match;
2307 }
2308 
2309 // Find the source range corresponding to the named type in the given
2310 // nested-name-specifier, if any.
2312  QualType T,
2313  const CXXScopeSpec &SS) {
2315  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2316  if (const Type *CurType = NNS->getAsType()) {
2317  if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2318  return NNSLoc.getTypeLoc().getSourceRange();
2319  } else
2320  break;
2321 
2322  NNSLoc = NNSLoc.getPrefix();
2323  }
2324 
2325  return SourceRange();
2326 }
2327 
2328 /// \brief Match the given template parameter lists to the given scope
2329 /// specifier, returning the template parameter list that applies to the
2330 /// name.
2331 ///
2332 /// \param DeclStartLoc the start of the declaration that has a scope
2333 /// specifier or a template parameter list.
2334 ///
2335 /// \param DeclLoc The location of the declaration itself.
2336 ///
2337 /// \param SS the scope specifier that will be matched to the given template
2338 /// parameter lists. This scope specifier precedes a qualified name that is
2339 /// being declared.
2340 ///
2341 /// \param TemplateId The template-id following the scope specifier, if there
2342 /// is one. Used to check for a missing 'template<>'.
2343 ///
2344 /// \param ParamLists the template parameter lists, from the outermost to the
2345 /// innermost template parameter lists.
2346 ///
2347 /// \param IsFriend Whether to apply the slightly different rules for
2348 /// matching template parameters to scope specifiers in friend
2349 /// declarations.
2350 ///
2351 /// \param IsMemberSpecialization will be set true if the scope specifier
2352 /// denotes a fully-specialized type, and therefore this is a declaration of
2353 /// a member specialization.
2354 ///
2355 /// \returns the template parameter list, if any, that corresponds to the
2356 /// name that is preceded by the scope specifier @p SS. This template
2357 /// parameter list may have template parameters (if we're declaring a
2358 /// template) or may have no template parameters (if we're declaring a
2359 /// template specialization), or may be NULL (if what we're declaring isn't
2360 /// itself a template).
2362  SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2363  TemplateIdAnnotation *TemplateId,
2364  ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2365  bool &IsMemberSpecialization, bool &Invalid) {
2366  IsMemberSpecialization = false;
2367  Invalid = false;
2368 
2369  // The sequence of nested types to which we will match up the template
2370  // parameter lists. We first build this list by starting with the type named
2371  // by the nested-name-specifier and walking out until we run out of types.
2372  SmallVector<QualType, 4> NestedTypes;
2373  QualType T;
2374  if (SS.getScopeRep()) {
2375  if (CXXRecordDecl *Record
2376  = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2377  T = Context.getTypeDeclType(Record);
2378  else
2379  T = QualType(SS.getScopeRep()->getAsType(), 0);
2380  }
2381 
2382  // If we found an explicit specialization that prevents us from needing
2383  // 'template<>' headers, this will be set to the location of that
2384  // explicit specialization.
2385  SourceLocation ExplicitSpecLoc;
2386 
2387  while (!T.isNull()) {
2388  NestedTypes.push_back(T);
2389 
2390  // Retrieve the parent of a record type.
2391  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2392  // If this type is an explicit specialization, we're done.
2394  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2395  if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2396  Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2397  ExplicitSpecLoc = Spec->getLocation();
2398  break;
2399  }
2400  } else if (Record->getTemplateSpecializationKind()
2402  ExplicitSpecLoc = Record->getLocation();
2403  break;
2404  }
2405 
2406  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2407  T = Context.getTypeDeclType(Parent);
2408  else
2409  T = QualType();
2410  continue;
2411  }
2412 
2413  if (const TemplateSpecializationType *TST
2415  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2416  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2417  T = Context.getTypeDeclType(Parent);
2418  else
2419  T = QualType();
2420  continue;
2421  }
2422  }
2423 
2424  // Look one step prior in a dependent template specialization type.
2425  if (const DependentTemplateSpecializationType *DependentTST
2427  if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2428  T = QualType(NNS->getAsType(), 0);
2429  else
2430  T = QualType();
2431  continue;
2432  }
2433 
2434  // Look one step prior in a dependent name type.
2435  if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2436  if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2437  T = QualType(NNS->getAsType(), 0);
2438  else
2439  T = QualType();
2440  continue;
2441  }
2442 
2443  // Retrieve the parent of an enumeration type.
2444  if (const EnumType *EnumT = T->getAs<EnumType>()) {
2445  // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2446  // check here.
2447  EnumDecl *Enum = EnumT->getDecl();
2448 
2449  // Get to the parent type.
2450  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2451  T = Context.getTypeDeclType(Parent);
2452  else
2453  T = QualType();
2454  continue;
2455  }
2456 
2457  T = QualType();
2458  }
2459  // Reverse the nested types list, since we want to traverse from the outermost
2460  // to the innermost while checking template-parameter-lists.
2461  std::reverse(NestedTypes.begin(), NestedTypes.end());
2462 
2463  // C++0x [temp.expl.spec]p17:
2464  // A member or a member template may be nested within many
2465  // enclosing class templates. In an explicit specialization for
2466  // such a member, the member declaration shall be preceded by a
2467  // template<> for each enclosing class template that is
2468  // explicitly specialized.
2469  bool SawNonEmptyTemplateParameterList = false;
2470 
2471  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2472  if (SawNonEmptyTemplateParameterList) {
2473  Diag(DeclLoc, diag::err_specialize_member_of_template)
2474  << !Recovery << Range;
2475  Invalid = true;
2476  IsMemberSpecialization = false;
2477  return true;
2478  }
2479 
2480  return false;
2481  };
2482 
2483  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2484  // Check that we can have an explicit specialization here.
2485  if (CheckExplicitSpecialization(Range, true))
2486  return true;
2487 
2488  // We don't have a template header, but we should.
2489  SourceLocation ExpectedTemplateLoc;
2490  if (!ParamLists.empty())
2491  ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2492  else
2493  ExpectedTemplateLoc = DeclStartLoc;
2494 
2495  Diag(DeclLoc, diag::err_template_spec_needs_header)
2496  << Range
2497  << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2498  return false;
2499  };
2500 
2501  unsigned ParamIdx = 0;
2502  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2503  ++TypeIdx) {
2504  T = NestedTypes[TypeIdx];
2505 
2506  // Whether we expect a 'template<>' header.
2507  bool NeedEmptyTemplateHeader = false;
2508 
2509  // Whether we expect a template header with parameters.
2510  bool NeedNonemptyTemplateHeader = false;
2511 
2512  // For a dependent type, the set of template parameters that we
2513  // expect to see.
2514  TemplateParameterList *ExpectedTemplateParams = nullptr;
2515 
2516  // C++0x [temp.expl.spec]p15:
2517  // A member or a member template may be nested within many enclosing
2518  // class templates. In an explicit specialization for such a member, the
2519  // member declaration shall be preceded by a template<> for each
2520  // enclosing class template that is explicitly specialized.
2521  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2523  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2524  ExpectedTemplateParams = Partial->getTemplateParameters();
2525  NeedNonemptyTemplateHeader = true;
2526  } else if (Record->isDependentType()) {
2527  if (Record->getDescribedClassTemplate()) {
2528  ExpectedTemplateParams = Record->getDescribedClassTemplate()
2529  ->getTemplateParameters();
2530  NeedNonemptyTemplateHeader = true;
2531  }
2532  } else if (ClassTemplateSpecializationDecl *Spec
2533  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2534  // C++0x [temp.expl.spec]p4:
2535  // Members of an explicitly specialized class template are defined
2536  // in the same manner as members of normal classes, and not using
2537  // the template<> syntax.
2538  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2539  NeedEmptyTemplateHeader = true;
2540  else
2541  continue;
2542  } else if (Record->getTemplateSpecializationKind()) {
2543  if (Record->getTemplateSpecializationKind()
2545  TypeIdx == NumTypes - 1)
2546  IsMemberSpecialization = true;
2547 
2548  continue;
2549  }
2550  } else if (const TemplateSpecializationType *TST
2552  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2553  ExpectedTemplateParams = Template->getTemplateParameters();
2554  NeedNonemptyTemplateHeader = true;
2555  }
2556  } else if (T->getAs<DependentTemplateSpecializationType>()) {
2557  // FIXME: We actually could/should check the template arguments here
2558  // against the corresponding template parameter list.
2559  NeedNonemptyTemplateHeader = false;
2560  }
2561 
2562  // C++ [temp.expl.spec]p16:
2563  // In an explicit specialization declaration for a member of a class
2564  // template or a member template that ap- pears in namespace scope, the
2565  // member template and some of its enclosing class templates may remain
2566  // unspecialized, except that the declaration shall not explicitly
2567  // specialize a class member template if its en- closing class templates
2568  // are not explicitly specialized as well.
2569  if (ParamIdx < ParamLists.size()) {
2570  if (ParamLists[ParamIdx]->size() == 0) {
2571  if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2572  false))
2573  return nullptr;
2574  } else
2575  SawNonEmptyTemplateParameterList = true;
2576  }
2577 
2578  if (NeedEmptyTemplateHeader) {
2579  // If we're on the last of the types, and we need a 'template<>' header
2580  // here, then it's a member specialization.
2581  if (TypeIdx == NumTypes - 1)
2582  IsMemberSpecialization = true;
2583 
2584  if (ParamIdx < ParamLists.size()) {
2585  if (ParamLists[ParamIdx]->size() > 0) {
2586  // The header has template parameters when it shouldn't. Complain.
2587  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2588  diag::err_template_param_list_matches_nontemplate)
2589  << T
2590  << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2591  ParamLists[ParamIdx]->getRAngleLoc())
2592  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2593  Invalid = true;
2594  return nullptr;
2595  }
2596 
2597  // Consume this template header.
2598  ++ParamIdx;
2599  continue;
2600  }
2601 
2602  if (!IsFriend)
2603  if (DiagnoseMissingExplicitSpecialization(
2604  getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2605  return nullptr;
2606 
2607  continue;
2608  }
2609 
2610  if (NeedNonemptyTemplateHeader) {
2611  // In friend declarations we can have template-ids which don't
2612  // depend on the corresponding template parameter lists. But
2613  // assume that empty parameter lists are supposed to match this
2614  // template-id.
2615  if (IsFriend && T->isDependentType()) {
2616  if (ParamIdx < ParamLists.size() &&
2617  DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2618  ExpectedTemplateParams = nullptr;
2619  else
2620  continue;
2621  }
2622 
2623  if (ParamIdx < ParamLists.size()) {
2624  // Check the template parameter list, if we can.
2625  if (ExpectedTemplateParams &&
2626  !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2627  ExpectedTemplateParams,
2628  true, TPL_TemplateMatch))
2629  Invalid = true;
2630 
2631  if (!Invalid &&
2632  CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2633  TPC_ClassTemplateMember))
2634  Invalid = true;
2635 
2636  ++ParamIdx;
2637  continue;
2638  }
2639 
2640  Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2641  << T
2642  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2643  Invalid = true;
2644  continue;
2645  }
2646  }
2647 
2648  // If there were at least as many template-ids as there were template
2649  // parameter lists, then there are no template parameter lists remaining for
2650  // the declaration itself.
2651  if (ParamIdx >= ParamLists.size()) {
2652  if (TemplateId && !IsFriend) {
2653  // We don't have a template header for the declaration itself, but we
2654  // should.
2655  DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2656  TemplateId->RAngleLoc));
2657 
2658  // Fabricate an empty template parameter list for the invented header.
2660  SourceLocation(), None,
2661  SourceLocation(), nullptr);
2662  }
2663 
2664  return nullptr;
2665  }
2666 
2667  // If there were too many template parameter lists, complain about that now.
2668  if (ParamIdx < ParamLists.size() - 1) {
2669  bool HasAnyExplicitSpecHeader = false;
2670  bool AllExplicitSpecHeaders = true;
2671  for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2672  if (ParamLists[I]->size() == 0)
2673  HasAnyExplicitSpecHeader = true;
2674  else
2675  AllExplicitSpecHeaders = false;
2676  }
2677 
2678  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2679  AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2680  : diag::err_template_spec_extra_headers)
2681  << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2682  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2683 
2684  // If there was a specialization somewhere, such that 'template<>' is
2685  // not required, and there were any 'template<>' headers, note where the
2686  // specialization occurred.
2687  if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2688  Diag(ExplicitSpecLoc,
2689  diag::note_explicit_template_spec_does_not_need_header)
2690  << NestedTypes.back();
2691 
2692  // We have a template parameter list with no corresponding scope, which
2693  // means that the resulting template declaration can't be instantiated
2694  // properly (we'll end up with dependent nodes when we shouldn't).
2695  if (!AllExplicitSpecHeaders)
2696  Invalid = true;
2697  }
2698 
2699  // C++ [temp.expl.spec]p16:
2700  // In an explicit specialization declaration for a member of a class
2701  // template or a member template that ap- pears in namespace scope, the
2702  // member template and some of its enclosing class templates may remain
2703  // unspecialized, except that the declaration shall not explicitly
2704  // specialize a class member template if its en- closing class templates
2705  // are not explicitly specialized as well.
2706  if (ParamLists.back()->size() == 0 &&
2707  CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2708  false))
2709  return nullptr;
2710 
2711  // Return the last template parameter list, which corresponds to the
2712  // entity being declared.
2713  return ParamLists.back();
2714 }
2715 
2717  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2718  Diag(Template->getLocation(), diag::note_template_declared_here)
2719  << (isa<FunctionTemplateDecl>(Template)
2720  ? 0
2721  : isa<ClassTemplateDecl>(Template)
2722  ? 1
2723  : isa<VarTemplateDecl>(Template)
2724  ? 2
2725  : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2726  << Template->getDeclName();
2727  return;
2728  }
2729 
2731  for (OverloadedTemplateStorage::iterator I = OST->begin(),
2732  IEnd = OST->end();
2733  I != IEnd; ++I)
2734  Diag((*I)->getLocation(), diag::note_template_declared_here)
2735  << 0 << (*I)->getDeclName();
2736 
2737  return;
2738  }
2739 }
2740 
2741 static QualType
2743  const SmallVectorImpl<TemplateArgument> &Converted,
2744  SourceLocation TemplateLoc,
2745  TemplateArgumentListInfo &TemplateArgs) {
2746  ASTContext &Context = SemaRef.getASTContext();
2747  switch (BTD->getBuiltinTemplateKind()) {
2748  case BTK__make_integer_seq: {
2749  // Specializations of __make_integer_seq<S, T, N> are treated like
2750  // S<T, 0, ..., N-1>.
2751 
2752  // C++14 [inteseq.intseq]p1:
2753  // T shall be an integer type.
2754  if (!Converted[1].getAsType()->isIntegralType(Context)) {
2755  SemaRef.Diag(TemplateArgs[1].getLocation(),
2756  diag::err_integer_sequence_integral_element_type);
2757  return QualType();
2758  }
2759 
2760  // C++14 [inteseq.make]p1:
2761  // If N is negative the program is ill-formed.
2762  TemplateArgument NumArgsArg = Converted[2];
2763  llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2764  if (NumArgs < 0) {
2765  SemaRef.Diag(TemplateArgs[2].getLocation(),
2766  diag::err_integer_sequence_negative_length);
2767  return QualType();
2768  }
2769 
2770  QualType ArgTy = NumArgsArg.getIntegralType();
2771  TemplateArgumentListInfo SyntheticTemplateArgs;
2772  // The type argument gets reused as the first template argument in the
2773  // synthetic template argument list.
2774  SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2775  // Expand N into 0 ... N-1.
2776  for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2777  I < NumArgs; ++I) {
2778  TemplateArgument TA(Context, I, ArgTy);
2779  SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2780  TA, ArgTy, TemplateArgs[2].getLocation()));
2781  }
2782  // The first template argument will be reused as the template decl that
2783  // our synthetic template arguments will be applied to.
2784  return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2785  TemplateLoc, SyntheticTemplateArgs);
2786  }
2787 
2789  // Specializations of
2790  // __type_pack_element<Index, T_1, ..., T_N>
2791  // are treated like T_Index.
2792  assert(Converted.size() == 2 &&
2793  "__type_pack_element should be given an index and a parameter pack");
2794 
2795  // If the Index is out of bounds, the program is ill-formed.
2796  TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2797  llvm::APSInt Index = IndexArg.getAsIntegral();
2798  assert(Index >= 0 && "the index used with __type_pack_element should be of "
2799  "type std::size_t, and hence be non-negative");
2800  if (Index >= Ts.pack_size()) {
2801  SemaRef.Diag(TemplateArgs[0].getLocation(),
2802  diag::err_type_pack_element_out_of_bounds);
2803  return QualType();
2804  }
2805 
2806  // We simply return the type at index `Index`.
2807  auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2808  return Nth->getAsType();
2809  }
2810  llvm_unreachable("unexpected BuiltinTemplateDecl!");
2811 }
2812 
2813 /// Determine whether this alias template is "enable_if_t".
2814 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2815  return AliasTemplate->getName().equals("enable_if_t");
2816 }
2817 
2818 /// Collect all of the separable terms in the given condition, which
2819 /// might be a conjunction.
2820 ///
2821 /// FIXME: The right answer is to convert the logical expression into
2822 /// disjunctive normal form, so we can find the first failed term
2823 /// within each possible clause.
2824 static void collectConjunctionTerms(Expr *Clause,
2825  SmallVectorImpl<Expr *> &Terms) {
2826  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2827  if (BinOp->getOpcode() == BO_LAnd) {
2828  collectConjunctionTerms(BinOp->getLHS(), Terms);
2829  collectConjunctionTerms(BinOp->getRHS(), Terms);
2830  }
2831 
2832  return;
2833  }
2834 
2835  Terms.push_back(Clause);
2836 }
2837 
2838 // The ranges-v3 library uses an odd pattern of a top-level "||" with
2839 // a left-hand side that is value-dependent but never true. Identify
2840 // the idiom and ignore that term.
2842  // Top-level '||'.
2843  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2844  if (!BinOp) return Cond;
2845 
2846  if (BinOp->getOpcode() != BO_LOr) return Cond;
2847 
2848  // With an inner '==' that has a literal on the right-hand side.
2849  Expr *LHS = BinOp->getLHS();
2850  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
2851  if (!InnerBinOp) return Cond;
2852 
2853  if (InnerBinOp->getOpcode() != BO_EQ ||
2854  !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2855  return Cond;
2856 
2857  // If the inner binary operation came from a macro expansion named
2858  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2859  // of the '||', which is the real, user-provided condition.
2860  SourceLocation Loc = InnerBinOp->getExprLoc();
2861  if (!Loc.isMacroID()) return Cond;
2862 
2863  StringRef MacroName = PP.getImmediateMacroName(Loc);
2864  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2865  return BinOp->getRHS();
2866 
2867  return Cond;
2868 }
2869 
2870 std::pair<Expr *, std::string>
2871 Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2872  Cond = lookThroughRangesV3Condition(PP, Cond);
2873 
2874  // Separate out all of the terms in a conjunction.
2875  SmallVector<Expr *, 4> Terms;
2876  collectConjunctionTerms(Cond, Terms);
2877 
2878  // Determine which term failed.
2879  Expr *FailedCond = nullptr;
2880  for (Expr *Term : Terms) {
2881  Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2882 
2883  // Literals are uninteresting.
2884  if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2885  isa<IntegerLiteral>(TermAsWritten))
2886  continue;
2887 
2888  // The initialization of the parameter from the argument is
2889  // a constant-evaluated context.
2890  EnterExpressionEvaluationContext ConstantEvaluated(
2892 
2893  bool Succeeded;
2894  if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
2895  !Succeeded) {
2896  FailedCond = TermAsWritten;
2897  break;
2898  }
2899  }
2900 
2901  if (!FailedCond) {
2902  if (!AllowTopLevelCond)
2903  return { nullptr, "" };
2904 
2905  FailedCond = Cond->IgnoreParenImpCasts();
2906  }
2907 
2908  std::string Description;
2909  {
2910  llvm::raw_string_ostream Out(Description);
2911  FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
2912  }
2913  return { FailedCond, Description };
2914 }
2915 
2917  SourceLocation TemplateLoc,
2918  TemplateArgumentListInfo &TemplateArgs) {
2921  if (DTN && DTN->isIdentifier())
2922  // When building a template-id where the template-name is dependent,
2923  // assume the template is a type template. Either our assumption is
2924  // correct, or the code is ill-formed and will be diagnosed when the
2925  // dependent name is substituted.
2927  DTN->getQualifier(),
2928  DTN->getIdentifier(),
2929  TemplateArgs);
2930 
2931  TemplateDecl *Template = Name.getAsTemplateDecl();
2932  if (!Template || isa<FunctionTemplateDecl>(Template) ||
2933  isa<VarTemplateDecl>(Template)) {
2934  // We might have a substituted template template parameter pack. If so,
2935  // build a template specialization type for it.
2937  return Context.getTemplateSpecializationType(Name, TemplateArgs);
2938 
2939  Diag(TemplateLoc, diag::err_template_id_not_a_type)
2940  << Name;
2941  NoteAllFoundTemplates(Name);
2942  return QualType();
2943  }
2944 
2945  // Check that the template argument list is well-formed for this
2946  // template.
2948  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2949  false, Converted))
2950  return QualType();
2951 
2952  QualType CanonType;
2953 
2954  bool InstantiationDependent = false;
2955  if (TypeAliasTemplateDecl *AliasTemplate =
2956  dyn_cast<TypeAliasTemplateDecl>(Template)) {
2957  // Find the canonical type for this type alias template specialization.
2958  TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2959  if (Pattern->isInvalidDecl())
2960  return QualType();
2961 
2963  Converted);
2964 
2965  // Only substitute for the innermost template argument list.
2966  MultiLevelTemplateArgumentList TemplateArgLists;
2967  TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
2968  unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2969  for (unsigned I = 0; I < Depth; ++I)
2970  TemplateArgLists.addOuterTemplateArguments(None);
2971 
2973  InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2974  if (Inst.isInvalid())
2975  return QualType();
2976 
2977  CanonType = SubstType(Pattern->getUnderlyingType(),
2978  TemplateArgLists, AliasTemplate->getLocation(),
2979  AliasTemplate->getDeclName());
2980  if (CanonType.isNull()) {
2981  // If this was enable_if and we failed to find the nested type
2982  // within enable_if in a SFINAE context, dig out the specific
2983  // enable_if condition that failed and present that instead.
2984  if (isEnableIfAliasTemplate(AliasTemplate)) {
2985  if (auto DeductionInfo = isSFINAEContext()) {
2986  if (*DeductionInfo &&
2987  (*DeductionInfo)->hasSFINAEDiagnostic() &&
2988  (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
2989  diag::err_typename_nested_not_found_enable_if &&
2990  TemplateArgs[0].getArgument().getKind()
2992  Expr *FailedCond;
2993  std::string FailedDescription;
2994  std::tie(FailedCond, FailedDescription) =
2995  findFailedBooleanCondition(
2996  TemplateArgs[0].getSourceExpression(),
2997  /*AllowTopLevelCond=*/true);
2998 
2999  // Remove the old SFINAE diagnostic.
3000  PartialDiagnosticAt OldDiag =
3002  (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3003 
3004  // Add a new SFINAE diagnostic specifying which condition
3005  // failed.
3006  (*DeductionInfo)->addSFINAEDiagnostic(
3007  OldDiag.first,
3008  PDiag(diag::err_typename_nested_not_found_requirement)
3009  << FailedDescription
3010  << FailedCond->getSourceRange());
3011  }
3012  }
3013  }
3014 
3015  return QualType();
3016  }
3017  } else if (Name.isDependent() ||
3019  TemplateArgs, InstantiationDependent)) {
3020  // This class template specialization is a dependent
3021  // type. Therefore, its canonical type is another class template
3022  // specialization type that contains all of the converted
3023  // arguments in canonical form. This ensures that, e.g., A<T> and
3024  // A<T, T> have identical types when A is declared as:
3025  //
3026  // template<typename T, typename U = T> struct A;
3027  CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3028 
3029  // This might work out to be a current instantiation, in which
3030  // case the canonical type needs to be the InjectedClassNameType.
3031  //
3032  // TODO: in theory this could be a simple hashtable lookup; most
3033  // changes to CurContext don't change the set of current
3034  // instantiations.
3035  if (isa<ClassTemplateDecl>(Template)) {
3036  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3037  // If we get out to a namespace, we're done.
3038  if (Ctx->isFileContext()) break;
3039 
3040  // If this isn't a record, keep looking.
3041  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3042  if (!Record) continue;
3043 
3044  // Look for one of the two cases with InjectedClassNameTypes
3045  // and check whether it's the same template.
3046  if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3047  !Record->getDescribedClassTemplate())
3048  continue;
3049 
3050  // Fetch the injected class name type and check whether its
3051  // injected type is equal to the type we just built.
3052  QualType ICNT = Context.getTypeDeclType(Record);
3053  QualType Injected = cast<InjectedClassNameType>(ICNT)
3054  ->getInjectedSpecializationType();
3055 
3056  if (CanonType != Injected->getCanonicalTypeInternal())
3057  continue;
3058 
3059  // If so, the canonical type of this TST is the injected
3060  // class name type of the record we just found.
3061  assert(ICNT.isCanonical());
3062  CanonType = ICNT;
3063  break;
3064  }
3065  }
3066  } else if (ClassTemplateDecl *ClassTemplate
3067  = dyn_cast<ClassTemplateDecl>(Template)) {
3068  // Find the class template specialization declaration that
3069  // corresponds to these arguments.
3070  void *InsertPos = nullptr;
3072  = ClassTemplate->findSpecialization(Converted, InsertPos);
3073  if (!Decl) {
3074  // This is the first time we have referenced this class template
3075  // specialization. Create the canonical declaration and add it to
3076  // the set of specializations.
3078  ClassTemplate->getTemplatedDecl()->getTagKind(),
3079  ClassTemplate->getDeclContext(),
3080  ClassTemplate->getTemplatedDecl()->getLocStart(),
3081  ClassTemplate->getLocation(),
3082  ClassTemplate,
3083  Converted, nullptr);
3084  ClassTemplate->AddSpecialization(Decl, InsertPos);
3085  if (ClassTemplate->isOutOfLine())
3086  Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3087  }
3088 
3089  if (Decl->getSpecializationKind() == TSK_Undeclared) {
3090  MultiLevelTemplateArgumentList TemplateArgLists;
3091  TemplateArgLists.addOuterTemplateArguments(Converted);
3092  InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3093  Decl);
3094  }
3095 
3096  // Diagnose uses of this specialization.
3097  (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3098 
3099  CanonType = Context.getTypeDeclType(Decl);
3100  assert(isa<RecordType>(CanonType) &&
3101  "type of non-dependent specialization is not a RecordType");
3102  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3103  CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3104  TemplateArgs);
3105  }
3106 
3107  // Build the fully-sugared type for this class template
3108  // specialization, which refers back to the class template
3109  // specialization we created or found.
3110  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3111 }
3112 
3113 TypeResult
3115  TemplateTy TemplateD, IdentifierInfo *TemplateII,
3116  SourceLocation TemplateIILoc,
3117  SourceLocation LAngleLoc,
3118  ASTTemplateArgsPtr TemplateArgsIn,
3119  SourceLocation RAngleLoc,
3120  bool IsCtorOrDtorName, bool IsClassName) {
3121  if (SS.isInvalid())
3122  return true;
3123 
3124  if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3125  DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3126 
3127  // C++ [temp.res]p3:
3128  // A qualified-id that refers to a type and in which the
3129  // nested-name-specifier depends on a template-parameter (14.6.2)
3130  // shall be prefixed by the keyword typename to indicate that the
3131  // qualified-id denotes a type, forming an
3132  // elaborated-type-specifier (7.1.5.3).
3133  if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3134  Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3135  << SS.getScopeRep() << TemplateII->getName();
3136  // Recover as if 'typename' were specified.
3137  // FIXME: This is not quite correct recovery as we don't transform SS
3138  // into the corresponding dependent form (and we don't diagnose missing
3139  // 'template' keywords within SS as a result).
3140  return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3141  TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3142  TemplateArgsIn, RAngleLoc);
3143  }
3144 
3145  // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3146  // it's not actually allowed to be used as a type in most cases. Because
3147  // we annotate it before we know whether it's valid, we have to check for
3148  // this case here.
3149  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3150  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3151  Diag(TemplateIILoc,
3152  TemplateKWLoc.isInvalid()
3153  ? diag::err_out_of_line_qualified_id_type_names_constructor
3154  : diag::ext_out_of_line_qualified_id_type_names_constructor)
3155  << TemplateII << 0 /*injected-class-name used as template name*/
3156  << 1 /*if any keyword was present, it was 'template'*/;
3157  }
3158  }
3159 
3160  TemplateName Template = TemplateD.get();
3161 
3162  // Translate the parser's template argument list in our AST format.
3163  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3164  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3165 
3166  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3167  QualType T
3169  DTN->getQualifier(),
3170  DTN->getIdentifier(),
3171  TemplateArgs);
3172  // Build type-source information.
3173  TypeLocBuilder TLB;
3177  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3178  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3179  SpecTL.setTemplateNameLoc(TemplateIILoc);
3180  SpecTL.setLAngleLoc(LAngleLoc);
3181  SpecTL.setRAngleLoc(RAngleLoc);
3182  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3183  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3184  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3185  }
3186 
3187  QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3188  if (Result.isNull())
3189  return true;
3190 
3191  // Build type-source information.
3192  TypeLocBuilder TLB;
3194  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3195  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3196  SpecTL.setTemplateNameLoc(TemplateIILoc);
3197  SpecTL.setLAngleLoc(LAngleLoc);
3198  SpecTL.setRAngleLoc(RAngleLoc);
3199  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3200  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3201 
3202  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3203  // constructor or destructor name (in such a case, the scope specifier
3204  // will be attached to the enclosing Decl or Expr node).
3205  if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3206  // Create an elaborated-type-specifier containing the nested-name-specifier.
3207  Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3208  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3210  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3211  }
3212 
3213  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3214 }
3215 
3217  TypeSpecifierType TagSpec,
3218  SourceLocation TagLoc,
3219  CXXScopeSpec &SS,
3220  SourceLocation TemplateKWLoc,
3221  TemplateTy TemplateD,
3222  SourceLocation TemplateLoc,
3223  SourceLocation LAngleLoc,
3224  ASTTemplateArgsPtr TemplateArgsIn,
3225  SourceLocation RAngleLoc) {
3226  TemplateName Template = TemplateD.get();
3227 
3228  // Translate the parser's template argument list in our AST format.
3229  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3230  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3231 
3232  // Determine the tag kind
3234  ElaboratedTypeKeyword Keyword
3236 
3237  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3239  DTN->getQualifier(),
3240  DTN->getIdentifier(),
3241  TemplateArgs);
3242 
3243  // Build type-source information.
3244  TypeLocBuilder TLB;
3247  SpecTL.setElaboratedKeywordLoc(TagLoc);
3248  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3249  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3250  SpecTL.setTemplateNameLoc(TemplateLoc);
3251  SpecTL.setLAngleLoc(LAngleLoc);
3252  SpecTL.setRAngleLoc(RAngleLoc);
3253  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3254  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3255  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3256  }
3257 
3258  if (TypeAliasTemplateDecl *TAT =
3259  dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3260  // C++0x [dcl.type.elab]p2:
3261  // If the identifier resolves to a typedef-name or the simple-template-id
3262  // resolves to an alias template specialization, the
3263  // elaborated-type-specifier is ill-formed.
3264  Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3265  << TAT << NTK_TypeAliasTemplate << TagKind;
3266  Diag(TAT->getLocation(), diag::note_declared_at);
3267  }
3268 
3269  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3270  if (Result.isNull())
3271  return TypeResult(true);
3272 
3273  // Check the tag kind
3274  if (const RecordType *RT = Result->getAs<RecordType>()) {
3275  RecordDecl *D = RT->getDecl();
3276 
3278  assert(Id && "templated class must have an identifier");
3279 
3280  if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3281  TagLoc, Id)) {
3282  Diag(TagLoc, diag::err_use_with_wrong_tag)
3283  << Result
3285  Diag(D->getLocation(), diag::note_previous_use);
3286  }
3287  }
3288 
3289  // Provide source-location information for the template specialization.
3290  TypeLocBuilder TLB;
3292  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3293  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3294  SpecTL.setTemplateNameLoc(TemplateLoc);
3295  SpecTL.setLAngleLoc(LAngleLoc);
3296  SpecTL.setRAngleLoc(RAngleLoc);
3297  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3298  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3299 
3300  // Construct an elaborated type containing the nested-name-specifier (if any)
3301  // and tag keyword.
3302  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3303  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3304  ElabTL.setElaboratedKeywordLoc(TagLoc);
3305  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3306  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3307 }
3308 
3309 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3310  NamedDecl *PrevDecl,
3311  SourceLocation Loc,
3313 
3315 
3317  const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3318  switch (Arg.getKind()) {
3325  return false;
3326 
3327  case TemplateArgument::Type: {
3328  QualType Type = Arg.getAsType();
3329  const TemplateTypeParmType *TPT =
3331  return TPT && !Type.hasQualifiers() &&
3332  TPT->getDepth() == Depth && TPT->getIndex() == Index;
3333  }
3334 
3336  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3337  if (!DRE || !DRE->getDecl())
3338  return false;
3339  const NonTypeTemplateParmDecl *NTTP =
3340  dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3341  return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3342  }
3343 
3345  const TemplateTemplateParmDecl *TTP =
3346  dyn_cast_or_null<TemplateTemplateParmDecl>(
3348  return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3349  }
3350  llvm_unreachable("unexpected kind of template argument");
3351 }
3352 
3355  if (Params->size() != Args.size())
3356  return false;
3357 
3358  unsigned Depth = Params->getDepth();
3359 
3360  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3361  TemplateArgument Arg = Args[I];
3362 
3363  // If the parameter is a pack expansion, the argument must be a pack
3364  // whose only element is a pack expansion.
3365  if (Params->getParam(I)->isParameterPack()) {
3366  if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3367  !Arg.pack_begin()->isPackExpansion())
3368  return false;
3369  Arg = Arg.pack_begin()->getPackExpansionPattern();
3370  }
3371 
3372  if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3373  return false;
3374  }
3375 
3376  return true;
3377 }
3378 
3379 /// Convert the parser's template argument list representation into our form.
3382  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3383  TemplateId.RAngleLoc);
3384  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3385  TemplateId.NumArgs);
3386  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3387  return TemplateArgs;
3388 }
3389 
3390 template<typename PartialSpecDecl>
3391 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3392  if (Partial->getDeclContext()->isDependentContext())
3393  return;
3394 
3395  // FIXME: Get the TDK from deduction in order to provide better diagnostics
3396  // for non-substitution-failure issues?
3397  TemplateDeductionInfo Info(Partial->getLocation());
3398  if (S.isMoreSpecializedThanPrimary(Partial, Info))
3399  return;
3400 
3401  auto *Template = Partial->getSpecializedTemplate();
3402  S.Diag(Partial->getLocation(),
3403  diag::ext_partial_spec_not_more_specialized_than_primary)
3404  << isa<VarTemplateDecl>(Template);
3405 
3406  if (Info.hasSFINAEDiagnostic()) {
3409  Info.takeSFINAEDiagnostic(Diag);
3410  SmallString<128> SFINAEArgString;
3411  Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3412  S.Diag(Diag.first,
3413  diag::note_partial_spec_not_more_specialized_than_primary)
3414  << SFINAEArgString;
3415  }
3416 
3417  S.Diag(Template->getLocation(), diag::note_template_decl_here);
3418 }
3419 
3420 static void
3422  const llvm::SmallBitVector &DeducibleParams) {
3423  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3424  if (!DeducibleParams[I]) {
3425  NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3426  if (Param->getDeclName())
3427  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3428  << Param->getDeclName();
3429  else
3430  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3431  << "(anonymous)";
3432  }
3433  }
3434 }
3435 
3436 
3437 template<typename PartialSpecDecl>
3439  PartialSpecDecl *Partial) {
3440  // C++1z [temp.class.spec]p8: (DR1495)
3441  // - The specialization shall be more specialized than the primary
3442  // template (14.5.5.2).
3443  checkMoreSpecializedThanPrimary(S, Partial);
3444 
3445  // C++ [temp.class.spec]p8: (DR1315)
3446  // - Each template-parameter shall appear at least once in the
3447  // template-id outside a non-deduced context.
3448  // C++1z [temp.class.spec.match]p3 (P0127R2)
3449  // If the template arguments of a partial specialization cannot be
3450  // deduced because of the structure of its template-parameter-list
3451  // and the template-id, the program is ill-formed.
3452  auto *TemplateParams = Partial->getTemplateParameters();
3453  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3454  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3455  TemplateParams->getDepth(), DeducibleParams);
3456 
3457  if (!DeducibleParams.all()) {
3458  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3459  S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3460  << isa<VarTemplatePartialSpecializationDecl>(Partial)
3461  << (NumNonDeducible > 1)
3462  << SourceRange(Partial->getLocation(),
3463  Partial->getTemplateArgsAsWritten()->RAngleLoc);
3464  noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3465  }
3466 }
3467 
3470  checkTemplatePartialSpecialization(*this, Partial);
3471 }
3472 
3475  checkTemplatePartialSpecialization(*this, Partial);
3476 }
3477 
3479  // C++1z [temp.param]p11:
3480  // A template parameter of a deduction guide template that does not have a
3481  // default-argument shall be deducible from the parameter-type-list of the
3482  // deduction guide template.
3483  auto *TemplateParams = TD->getTemplateParameters();
3484  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3485  MarkDeducedTemplateParameters(TD, DeducibleParams);
3486  for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3487  // A parameter pack is deducible (to an empty pack).
3488  auto *Param = TemplateParams->getParam(I);
3489  if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3490  DeducibleParams[I] = true;
3491  }
3492 
3493  if (!DeducibleParams.all()) {
3494  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3495  Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3496  << (NumNonDeducible > 1);
3497  noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3498  }
3499 }
3500 
3502  Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3503  TemplateParameterList *TemplateParams, StorageClass SC,
3504  bool IsPartialSpecialization) {
3505  // D must be variable template id.
3506  assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3507  "Variable template specialization is declared with a template it.");
3508 
3509  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3510  TemplateArgumentListInfo TemplateArgs =
3511  makeTemplateArgumentListInfo(*this, *TemplateId);
3512  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3513  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3514  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3515 
3516  TemplateName Name = TemplateId->Template.get();
3517 
3518  // The template-id must name a variable template.
3519  VarTemplateDecl *VarTemplate =
3520  dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3521  if (!VarTemplate) {
3522  NamedDecl *FnTemplate;
3523  if (auto *OTS = Name.getAsOverloadedTemplate())
3524  FnTemplate = *OTS->begin();
3525  else
3526  FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3527  if (FnTemplate)
3528  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3529  << FnTemplate->getDeclName();
3530  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3531  << IsPartialSpecialization;
3532  }
3533 
3534  // Check for unexpanded parameter packs in any of the template arguments.
3535  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3536  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3537  UPPC_PartialSpecialization))
3538  return true;
3539 
3540  // Check that the template argument list is well-formed for this
3541  // template.
3543  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3544  false, Converted))
3545  return true;
3546 
3547  // Find the variable template (partial) specialization declaration that
3548  // corresponds to these arguments.
3549  if (IsPartialSpecialization) {
3550  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3551  TemplateArgs.size(), Converted))
3552  return true;
3553 
3554  // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3555  // also do them during instantiation.
3556  bool InstantiationDependent;
3557  if (!Name.isDependent() &&
3559  TemplateArgs.arguments(),
3560  InstantiationDependent)) {
3561  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3562  << VarTemplate->getDeclName();
3563  IsPartialSpecialization = false;
3564  }
3565 
3567  Converted)) {
3568  // C++ [temp.class.spec]p9b3:
3569  //
3570  // -- The argument list of the specialization shall not be identical
3571  // to the implicit argument list of the primary template.
3572  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3573  << /*variable template*/ 1
3574  << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3575  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3576  // FIXME: Recover from this by treating the declaration as a redeclaration
3577  // of the primary template.
3578  return true;
3579  }
3580  }
3581 
3582  void *InsertPos = nullptr;
3583  VarTemplateSpecializationDecl *PrevDecl = nullptr;
3584 
3585  if (IsPartialSpecialization)
3586  // FIXME: Template parameter list matters too
3587  PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3588  else
3589  PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3590 
3591  VarTemplateSpecializationDecl *Specialization = nullptr;
3592 
3593  // Check whether we can declare a variable template specialization in
3594  // the current scope.
3595  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3596  TemplateNameLoc,
3597  IsPartialSpecialization))
3598  return true;
3599 
3600  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3601  // Since the only prior variable template specialization with these
3602  // arguments was referenced but not declared, reuse that
3603  // declaration node as our own, updating its source location and
3604  // the list of outer template parameters to reflect our new declaration.
3605  Specialization = PrevDecl;
3606  Specialization->setLocation(TemplateNameLoc);
3607  PrevDecl = nullptr;
3608  } else if (IsPartialSpecialization) {
3609  // Create a new class template partial specialization declaration node.
3611  cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3614  Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3615  TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3616  Converted, TemplateArgs);
3617 
3618  if (!PrevPartial)
3619  VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3620  Specialization = Partial;
3621 
3622  // If we are providing an explicit specialization of a member variable
3623  // template specialization, make a note of that.
3624  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3625  PrevPartial->setMemberSpecialization();
3626 
3627  CheckTemplatePartialSpecialization(Partial);
3628  } else {
3629  // Create a new class template specialization declaration node for
3630  // this explicit specialization or friend declaration.
3631  Specialization = VarTemplateSpecializationDecl::Create(
3632  Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3633  VarTemplate, DI->getType(), DI, SC, Converted);
3634  Specialization->setTemplateArgsInfo(TemplateArgs);
3635 
3636  if (!PrevDecl)
3637  VarTemplate->AddSpecialization(Specialization, InsertPos);
3638  }
3639 
3640  // C++ [temp.expl.spec]p6:
3641  // If a template, a member template or the member of a class template is
3642  // explicitly specialized then that specialization shall be declared
3643  // before the first use of that specialization that would cause an implicit
3644  // instantiation to take place, in every translation unit in which such a
3645  // use occurs; no diagnostic is required.
3646  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3647  bool Okay = false;
3648  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3649  // Is there any previous explicit specialization declaration?
3651  Okay = true;
3652  break;
3653  }
3654  }
3655 
3656  if (!Okay) {
3657  SourceRange Range(TemplateNameLoc, RAngleLoc);
3658  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3659  << Name << Range;
3660 
3661  Diag(PrevDecl->getPointOfInstantiation(),
3662  diag::note_instantiation_required_here)
3663  << (PrevDecl->getTemplateSpecializationKind() !=
3665  return true;
3666  }
3667  }
3668 
3669  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3670  Specialization->setLexicalDeclContext(CurContext);
3671 
3672  // Add the specialization into its lexical context, so that it can
3673  // be seen when iterating through the list of declarations in that
3674  // context. However, specializations are not found by name lookup.
3675  CurContext->addDecl(Specialization);
3676 
3677  // Note that this is an explicit specialization.
3679 
3680  if (PrevDecl) {
3681  // Check that this isn't a redefinition of this specialization,
3682  // merging with previous declarations.
3683  LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3684  forRedeclarationInCurContext());
3685  PrevSpec.addDecl(PrevDecl);
3686  D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3687  } else if (Specialization->isStaticDataMember() &&
3688  Specialization->isOutOfLine()) {
3689  Specialization->setAccess(VarTemplate->getAccess());
3690  }
3691 
3692  // Link instantiations of static data members back to the template from
3693  // which they were instantiated.
3694  if (Specialization->isStaticDataMember())
3695  Specialization->setInstantiationOfStaticDataMember(
3696  VarTemplate->getTemplatedDecl(),
3697  Specialization->getSpecializationKind());
3698 
3699  return Specialization;
3700 }
3701 
3702 namespace {
3703 /// \brief A partial specialization whose template arguments have matched
3704 /// a given template-id.
3705 struct PartialSpecMatchResult {
3707  TemplateArgumentList *Args;
3708 };
3709 } // end anonymous namespace
3710 
3711 DeclResult
3713  SourceLocation TemplateNameLoc,
3714  const TemplateArgumentListInfo &TemplateArgs) {
3715  assert(Template && "A variable template id without template?");
3716 
3717  // Check that the template argument list is well-formed for this template.
3719  if (CheckTemplateArgumentList(
3720  Template, TemplateNameLoc,
3721  const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3722  Converted))
3723  return true;
3724 
3725  // Find the variable template specialization declaration that
3726  // corresponds to these arguments.
3727  void *InsertPos = nullptr;
3728  if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3729  Converted, InsertPos)) {
3730  checkSpecializationVisibility(TemplateNameLoc, Spec);
3731  // If we already have a variable template specialization, return it.
3732  return Spec;
3733  }
3734 
3735  // This is the first time we have referenced this variable template
3736  // specialization. Create the canonical declaration and add it to
3737  // the set of specializations, based on the closest partial specialization
3738  // that it represents. That is,
3739  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3741  Converted);
3742  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3743  bool AmbiguousPartialSpec = false;
3744  typedef PartialSpecMatchResult MatchResult;
3746  SourceLocation PointOfInstantiation = TemplateNameLoc;
3747  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3748  /*ForTakingAddress=*/false);
3749 
3750  // 1. Attempt to find the closest partial specialization that this
3751  // specializes, if any.
3752  // If any of the template arguments is dependent, then this is probably
3753  // a placeholder for an incomplete declarative context; which must be
3754  // complete by instantiation time. Thus, do not search through the partial
3755  // specializations yet.
3756  // TODO: Unify with InstantiateClassTemplateSpecialization()?
3757  // Perhaps better after unification of DeduceTemplateArguments() and
3758  // getMoreSpecializedPartialSpecialization().
3759  bool InstantiationDependent = false;
3761  TemplateArgs, InstantiationDependent)) {
3762 
3764  Template->getPartialSpecializations(PartialSpecs);
3765 
3766  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3767  VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3768  TemplateDeductionInfo Info(FailedCandidates.getLocation());
3769 
3770  if (TemplateDeductionResult Result =
3771  DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3772  // Store the failed-deduction information for use in diagnostics, later.
3773  // TODO: Actually use the failed-deduction info?
3774  FailedCandidates.addCandidate().set(
3775  DeclAccessPair::make(Template, AS_public), Partial,
3776  MakeDeductionFailureInfo(Context, Result, Info));
3777  (void)Result;
3778  } else {
3779  Matched.push_back(PartialSpecMatchResult());
3780  Matched.back().Partial = Partial;
3781  Matched.back().Args = Info.take();
3782  }
3783  }
3784 
3785  if (Matched.size() >= 1) {
3786  SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3787  if (Matched.size() == 1) {
3788  // -- If exactly one matching specialization is found, the
3789  // instantiation is generated from that specialization.
3790  // We don't need to do anything for this.
3791  } else {
3792  // -- If more than one matching specialization is found, the
3793  // partial order rules (14.5.4.2) are used to determine
3794  // whether one of the specializations is more specialized
3795  // than the others. If none of the specializations is more
3796  // specialized than all of the other matching
3797  // specializations, then the use of the variable template is
3798  // ambiguous and the program is ill-formed.
3799  for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3800  PEnd = Matched.end();
3801  P != PEnd; ++P) {
3802  if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3803  PointOfInstantiation) ==
3804  P->Partial)
3805  Best = P;
3806  }
3807 
3808  // Determine if the best partial specialization is more specialized than
3809  // the others.
3810  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3811  PEnd = Matched.end();
3812  P != PEnd; ++P) {
3813  if (P != Best && getMoreSpecializedPartialSpecialization(
3814  P->Partial, Best->Partial,
3815  PointOfInstantiation) != Best->Partial) {
3816  AmbiguousPartialSpec = true;
3817  break;
3818  }
3819  }
3820  }
3821 
3822  // Instantiate using the best variable template partial specialization.
3823  InstantiationPattern = Best->Partial;
3824  InstantiationArgs = Best->Args;
3825  } else {
3826  // -- If no match is found, the instantiation is generated
3827  // from the primary template.
3828  // InstantiationPattern = Template->getTemplatedDecl();
3829  }
3830  }
3831 
3832  // 2. Create the canonical declaration.
3833  // Note that we do not instantiate a definition until we see an odr-use
3834  // in DoMarkVarDeclReferenced().
3835  // FIXME: LateAttrs et al.?
3836  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3837  Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3838  Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3839  if (!Decl)
3840  return true;
3841 
3842  if (AmbiguousPartialSpec) {
3843  // Partial ordering did not produce a clear winner. Complain.
3844  Decl->setInvalidDecl();
3845  Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3846  << Decl;
3847 
3848  // Print the matching partial specializations.
3849  for (MatchResult P : Matched)
3850  Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3851  << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3852  *P.Args);
3853  return true;
3854  }
3855 
3857  dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3858  Decl->setInstantiationOf(D, InstantiationArgs);
3859 
3860  checkSpecializationVisibility(TemplateNameLoc, Decl);
3861 
3862  assert(Decl && "No variable template specialization?");
3863  return Decl;
3864 }
3865 
3866 ExprResult
3868  const DeclarationNameInfo &NameInfo,
3869  VarTemplateDecl *Template, SourceLocation TemplateLoc,
3870  const TemplateArgumentListInfo *TemplateArgs) {
3871 
3872  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3873  *TemplateArgs);
3874  if (Decl.isInvalid())
3875  return ExprError();
3876 
3877  VarDecl *Var = cast<VarDecl>(Decl.get());
3878  if (!Var->getTemplateSpecializationKind())
3880  NameInfo.getLoc());
3881 
3882  // Build an ordinary singleton decl ref.
3883  return BuildDeclarationNameExpr(SS, NameInfo, Var,
3884  /*FoundD=*/nullptr, TemplateArgs);
3885 }
3886 
3888  SourceLocation TemplateKWLoc,
3889  LookupResult &R,
3890  bool RequiresADL,
3891  const TemplateArgumentListInfo *TemplateArgs) {
3892  // FIXME: Can we do any checking at this point? I guess we could check the
3893  // template arguments that we have against the template name, if the template
3894  // name refers to a single template. That's not a terribly common case,
3895  // though.
3896  // foo<int> could identify a single function unambiguously
3897  // This approach does NOT work, since f<int>(1);
3898  // gets resolved prior to resorting to overload resolution
3899  // i.e., template<class T> void f(double);
3900  // vs template<class T, class U> void f(U);
3901 
3902  // These should be filtered out by our callers.
3903  assert(!R.empty() && "empty lookup results when building templateid");
3904  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3905 
3906  // In C++1y, check variable template ids.
3907  bool InstantiationDependent;
3908  if (R.getAsSingle<VarTemplateDecl>() &&
3910  *TemplateArgs, InstantiationDependent)) {
3911  return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3913  TemplateKWLoc, TemplateArgs);
3914  }
3915 
3916  // We don't want lookup warnings at this point.
3917  R.suppressDiagnostics();
3918 
3921  SS.getWithLocInContext(Context),
3922  TemplateKWLoc,
3923  R.getLookupNameInfo(),
3924  RequiresADL, TemplateArgs,
3925  R.begin(), R.end());
3926 
3927  return ULE;
3928 }
3929 
3930 // We actually only call this from template instantiation.
3931 ExprResult
3933  SourceLocation TemplateKWLoc,
3934  const DeclarationNameInfo &NameInfo,
3935  const TemplateArgumentListInfo *TemplateArgs) {
3936 
3937  assert(TemplateArgs || TemplateKWLoc.isValid());
3938  DeclContext *DC;
3939  if (!(DC = computeDeclContext(SS, false)) ||
3940  DC->isDependentContext() ||
3941  RequireCompleteDeclContext(SS, DC))
3942  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3943 
3944  bool MemberOfUnknownSpecialization;
3945  LookupResult R(*this, NameInfo, LookupOrdinaryName);
3946  LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
3947  MemberOfUnknownSpecialization);
3948 
3949  if (R.isAmbiguous())
3950  return ExprError();
3951 
3952  if (R.empty()) {
3953  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3954  << NameInfo.getName() << SS.getRange();
3955  return ExprError();
3956  }
3957 
3958  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
3959  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3960  << SS.getScopeRep()
3961  << NameInfo.getName().getAsString() << SS.getRange();
3962  Diag(Temp->getLocation(), diag::note_referenced_class_template);
3963  return ExprError();
3964  }
3965 
3966  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
3967 }
3968 
3969 /// \brief Form a dependent template name.
3970 ///
3971 /// This action forms a dependent template name given the template
3972 /// name and its (presumably dependent) scope specifier. For
3973 /// example, given "MetaFun::template apply", the scope specifier \p
3974 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3975 /// of the "template" keyword, and "apply" is the \p Name.
3977  CXXScopeSpec &SS,
3978  SourceLocation TemplateKWLoc,
3979  UnqualifiedId &Name,
3980  ParsedType ObjectType,
3981  bool EnteringContext,
3982  TemplateTy &Result,
3983  bool AllowInjectedClassName) {
3984  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3985  Diag(TemplateKWLoc,
3986  getLangOpts().CPlusPlus11 ?
3987  diag::warn_cxx98_compat_template_outside_of_template :
3988  diag::ext_template_outside_of_template)
3989  << FixItHint::CreateRemoval(TemplateKWLoc);
3990 
3991  DeclContext *LookupCtx = nullptr;
3992  if (SS.isSet())
3993  LookupCtx = computeDeclContext(SS, EnteringContext);
3994  if (!LookupCtx && ObjectType)
3995  LookupCtx = computeDeclContext(ObjectType.get());
3996  if (LookupCtx) {
3997  // C++0x [temp.names]p5:
3998  // If a name prefixed by the keyword template is not the name of
3999  // a template, the program is ill-formed. [Note: the keyword
4000  // template may not be applied to non-template members of class
4001  // templates. -end note ] [ Note: as is the case with the
4002  // typename prefix, the template prefix is allowed in cases
4003  // where it is not strictly necessary; i.e., when the
4004  // nested-name-specifier or the expression on the left of the ->
4005  // or . is not dependent on a template-parameter, or the use
4006  // does not appear in the scope of a template. -end note]
4007  //
4008  // Note: C++03 was more strict here, because it banned the use of
4009  // the "template" keyword prior to a template-name that was not a
4010  // dependent name. C++ DR468 relaxed this requirement (the
4011  // "template" keyword is now permitted). We follow the C++0x
4012  // rules, even in C++03 mode with a warning, retroactively applying the DR.
4013  bool MemberOfUnknownSpecialization;
4014  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4015  ObjectType, EnteringContext, Result,
4016  MemberOfUnknownSpecialization);
4017  if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4018  isa<CXXRecordDecl>(LookupCtx) &&
4019  (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4020  cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
4021  // This is a dependent template. Handle it below.
4022  } else if (TNK == TNK_Non_template) {
4023  Diag(Name.getLocStart(),
4024  diag::err_template_kw_refers_to_non_template)
4025  << GetNameFromUnqualifiedId(Name).getName()
4026  << Name.getSourceRange()
4027  << TemplateKWLoc;
4028  return TNK_Non_template;
4029  } else {
4030  // We found something; return it.
4031  auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4032  if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4033  Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
4034  LookupRD->getIdentifier() == Name.Identifier) {
4035  // C++14 [class.qual]p2:
4036  // In a lookup in which function names are not ignored and the
4037  // nested-name-specifier nominates a class C, if the name specified
4038  // [...] is the injected-class-name of C, [...] the name is instead
4039  // considered to name the constructor
4040  //
4041  // We don't get here if naming the constructor would be valid, so we
4042  // just reject immediately and recover by treating the
4043  // injected-class-name as naming the template.
4044  Diag(Name.getLocStart(),
4045  diag::ext_out_of_line_qualified_id_type_names_constructor)
4046  << Name.Identifier << 0 /*injected-class-name used as template name*/
4047  << 1 /*'template' keyword was used*/;
4048  }
4049  return TNK;
4050  }
4051  }
4052 
4053  NestedNameSpecifier *Qualifier = SS.getScopeRep();
4054 
4055  switch (Name.getKind()) {
4057  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4058  Name.Identifier));
4060 
4062  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4064  return TNK_Function_template;
4065 
4067  llvm_unreachable("literal operator id cannot have a dependent scope");
4068 
4069  default:
4070  break;
4071  }
4072 
4073  Diag(Name.getLocStart(),
4074  diag::err_template_kw_refers_to_non_template)
4075  << GetNameFromUnqualifiedId(Name).getName()
4076  << Name.getSourceRange()
4077  << TemplateKWLoc;
4078  return TNK_Non_template;
4079 }
4080 
4082  TemplateArgumentLoc &AL,
4083  SmallVectorImpl<TemplateArgument> &Converted) {
4084  const TemplateArgument &Arg = AL.getArgument();
4085  QualType ArgType;
4086  TypeSourceInfo *TSI = nullptr;
4087 
4088  // Check template type parameter.
4089  switch(Arg.getKind()) {
4091  // C++ [temp.arg.type]p1:
4092  // A template-argument for a template-parameter which is a
4093  // type shall be a type-id.
4094  ArgType = Arg.getAsType();
4095  TSI = AL.getTypeSourceInfo();
4096  break;
4098  // We have a template type parameter but the template argument
4099  // is a template without any arguments.
4100  SourceRange SR = AL.getSourceRange();
4101  TemplateName Name = Arg.getAsTemplate();
4102  Diag(SR.getBegin(), diag::err_template_missing_args)
4103  << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
4104  if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4105  Diag(Decl->getLocation(), diag::note_template_decl_here);
4106 
4107  return true;
4108  }
4110  // We have a template type parameter but the template argument is an
4111  // expression; see if maybe it is missing the "typename" keyword.
4112  CXXScopeSpec SS;
4113  DeclarationNameInfo NameInfo;
4114 
4115  if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4116  SS.Adopt(ArgExpr->getQualifierLoc());
4117  NameInfo = ArgExpr->getNameInfo();
4118  } else if (DependentScopeDeclRefExpr *ArgExpr =
4119  dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4120  SS.Adopt(ArgExpr->getQualifierLoc());
4121  NameInfo = ArgExpr->getNameInfo();
4122  } else if (CXXDependentScopeMemberExpr *ArgExpr =
4123  dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4124  if (ArgExpr->isImplicitAccess()) {
4125  SS.Adopt(ArgExpr->getQualifierLoc());
4126  NameInfo = ArgExpr->getMemberNameInfo();
4127  }
4128  }
4129 
4130  if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4131  LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4132  LookupParsedName(Result, CurScope, &SS);
4133 
4134  if (Result.getAsSingle<TypeDecl>() ||
4135  Result.getResultKind() ==
4137  // Suggest that the user add 'typename' before the NNS.
4138  SourceLocation Loc = AL.getSourceRange().getBegin();
4139  Diag(Loc, getLangOpts().MSVCCompat
4140  ? diag::ext_ms_template_type_arg_missing_typename
4141  : diag::err_template_arg_must_be_type_suggest)
4142  << FixItHint::CreateInsertion(Loc, "typename ");
4143  Diag(Param->getLocation(), diag::note_template_param_here);
4144 
4145  // Recover by synthesizing a type using the location information that we
4146  // already have.
4147  ArgType =
4148  Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4149  TypeLocBuilder TLB;
4150  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4151  TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4152  TL.setQualifierLoc(SS.getWithLocInContext(Context));
4153  TL.setNameLoc(NameInfo.getLoc());
4154  TSI = TLB.getTypeSourceInfo(Context, ArgType);
4155 
4156  // Overwrite our input TemplateArgumentLoc so that we can recover
4157  // properly.
4158  AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4160 
4161  break;
4162  }
4163  }
4164  // fallthrough
4165  LLVM_FALLTHROUGH;
4166  }
4167  default: {
4168  // We have a template type parameter but the template argument
4169  // is not a type.
4170  SourceRange SR = AL.getSourceRange();
4171  Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4172  Diag(Param->getLocation(), diag::note_template_param_here);
4173 
4174  return true;
4175  }
4176  }
4177 
4178  if (CheckTemplateArgument(Param, TSI))
4179  return true;
4180 
4181  // Add the converted template type argument.
4182  ArgType = Context.getCanonicalType(ArgType);
4183 
4184  // Objective-C ARC:
4185  // If an explicitly-specified template argument type is a lifetime type
4186  // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4187  if (getLangOpts().ObjCAutoRefCount &&
4188  ArgType->isObjCLifetimeType() &&
4189  !ArgType.getObjCLifetime()) {
4190  Qualifiers Qs;
4192  ArgType = Context.getQualifiedType(ArgType, Qs);
4193  }
4194 
4195  Converted.push_back(TemplateArgument(ArgType));
4196  return false;
4197 }
4198 
4199 /// \brief Substitute template arguments into the default template argument for
4200 /// the given template type parameter.
4201 ///
4202 /// \param SemaRef the semantic analysis object for which we are performing
4203 /// the substitution.
4204 ///
4205 /// \param Template the template that we are synthesizing template arguments
4206 /// for.
4207 ///
4208 /// \param TemplateLoc the location of the template name that started the
4209 /// template-id we are checking.
4210 ///
4211 /// \param RAngleLoc the location of the right angle bracket ('>') that
4212 /// terminates the template-id.
4213 ///
4214 /// \param Param the template template parameter whose default we are
4215 /// substituting into.
4216 ///
4217 /// \param Converted the list of template arguments provided for template
4218 /// parameters that precede \p Param in the template parameter list.
4219 /// \returns the substituted template argument, or NULL if an error occurred.
4220 static TypeSourceInfo *
4222  TemplateDecl *Template,
4223  SourceLocation TemplateLoc,
4224  SourceLocation RAngleLoc,
4225  TemplateTypeParmDecl *Param,
4226  SmallVectorImpl<TemplateArgument> &Converted) {
4227  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4228 
4229  // If the argument type is dependent, instantiate it now based
4230  // on the previously-computed template arguments.
4231  if (ArgType->getType()->isDependentType()) {
4232  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4233  Param, Template, Converted,
4234  SourceRange(TemplateLoc, RAngleLoc));
4235  if (Inst.isInvalid())
4236  return nullptr;
4237 
4238  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4239 
4240  // Only substitute for the innermost template argument list.
4241  MultiLevelTemplateArgumentList TemplateArgLists;
4242  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4243  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4244  TemplateArgLists.addOuterTemplateArguments(None);
4245 
4246  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4247  ArgType =
4248  SemaRef.SubstType(ArgType, TemplateArgLists,
4249  Param->getDefaultArgumentLoc(), Param->getDeclName());
4250  }
4251 
4252  return ArgType;
4253 }
4254 
4255 /// \brief Substitute template arguments into the default template argument for
4256 /// the given non-type template parameter.
4257 ///
4258 /// \param SemaRef the semantic analysis object for which we are performing
4259 /// the substitution.
4260 ///
4261 /// \param Template the template that we are synthesizing template arguments
4262 /// for.
4263 ///
4264 /// \param TemplateLoc the location of the template name that started the
4265 /// template-id we are checking.
4266 ///
4267 /// \param RAngleLoc the location of the right angle bracket ('>') that
4268 /// terminates the template-id.
4269 ///
4270 /// \param Param the non-type template parameter whose default we are
4271 /// substituting into.
4272 ///
4273 /// \param Converted the list of template arguments provided for template
4274 /// parameters that precede \p Param in the template parameter list.
4275 ///
4276 /// \returns the substituted template argument, or NULL if an error occurred.
4277 static ExprResult
4279  TemplateDecl *Template,
4280  SourceLocation TemplateLoc,
4281  SourceLocation RAngleLoc,
4282  NonTypeTemplateParmDecl *Param,
4283  SmallVectorImpl<TemplateArgument> &Converted) {
4284  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4285  Param, Template, Converted,
4286  SourceRange(TemplateLoc, RAngleLoc));
4287  if (Inst.isInvalid())
4288  return ExprError();
4289 
4290  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4291 
4292  // Only substitute for the innermost template argument list.
4293  MultiLevelTemplateArgumentList TemplateArgLists;
4294  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4295  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4296  TemplateArgLists.addOuterTemplateArguments(None);
4297 
4298  EnterExpressionEvaluationContext ConstantEvaluated(
4300  return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4301 }
4302 
4303 /// \brief Substitute template arguments into the default template argument for
4304 /// the given template template parameter.
4305 ///
4306 /// \param SemaRef the semantic analysis object for which we are performing
4307 /// the substitution.
4308 ///
4309 /// \param Template the template that we are synthesizing template arguments
4310 /// for.
4311 ///
4312 /// \param TemplateLoc the location of the template name that started the
4313 /// template-id we are checking.
4314 ///
4315 /// \param RAngleLoc the location of the right angle bracket ('>') that
4316 /// terminates the template-id.
4317 ///
4318 /// \param Param the template template parameter whose default we are
4319 /// substituting into.
4320 ///
4321 /// \param Converted the list of template arguments provided for template
4322 /// parameters that precede \p Param in the template parameter list.
4323 ///
4324 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4325 /// source-location information) that precedes the template name.
4326 ///
4327 /// \returns the substituted template argument, or NULL if an error occurred.
4328 static TemplateName
4330  TemplateDecl *Template,
4331  SourceLocation TemplateLoc,
4332  SourceLocation RAngleLoc,
4333  TemplateTemplateParmDecl *Param,
4335  NestedNameSpecifierLoc &QualifierLoc) {
4337  SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4338  SourceRange(TemplateLoc, RAngleLoc));
4339  if (Inst.isInvalid())
4340  return TemplateName();
4341 
4342  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4343 
4344  // Only substitute for the innermost template argument list.
4345  MultiLevelTemplateArgumentList TemplateArgLists;
4346  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4347  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4348  TemplateArgLists.addOuterTemplateArguments(None);
4349 
4350  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4351  // Substitute into the nested-name-specifier first,
4352  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4353  if (QualifierLoc) {
4354  QualifierLoc =
4355  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4356  if (!QualifierLoc)
4357  return TemplateName();
4358  }
4359 
4360  return SemaRef.SubstTemplateName(
4361  QualifierLoc,
4364  TemplateArgLists);
4365 }
4366 
4367 /// \brief If the given template parameter has a default template
4368 /// argument, substitute into that default template argument and
4369 /// return the corresponding template argument.
4372  SourceLocation TemplateLoc,
4373  SourceLocation RAngleLoc,
4374  Decl *Param,
4376  &Converted,
4377  bool &HasDefaultArg) {
4378  HasDefaultArg = false;
4379 
4380  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4381  if (!hasVisibleDefaultArgument(TypeParm))
4382  return TemplateArgumentLoc();
4383 
4384  HasDefaultArg = true;
4385  TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4386  TemplateLoc,
4387  RAngleLoc,
4388  TypeParm,
4389  Converted);
4390  if (DI)
4391  return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4392 
4393  return TemplateArgumentLoc();
4394  }
4395 
4396  if (NonTypeTemplateParmDecl *NonTypeParm
4397  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4398  if (!hasVisibleDefaultArgument(NonTypeParm))
4399  return TemplateArgumentLoc();
4400 
4401  HasDefaultArg = true;
4402  ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4403  TemplateLoc,
4404  RAngleLoc,
4405  NonTypeParm,
4406  Converted);
4407  if (Arg.isInvalid())
4408  return TemplateArgumentLoc();
4409 
4410  Expr *ArgE = Arg.getAs<Expr>();
4411  return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4412  }
4413 
4414  TemplateTemplateParmDecl *TempTempParm
4415  = cast<TemplateTemplateParmDecl>(Param);
4416  if (!hasVisibleDefaultArgument(TempTempParm))
4417  return TemplateArgumentLoc();
4418 
4419  HasDefaultArg = true;
4420  NestedNameSpecifierLoc QualifierLoc;
4421  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4422  TemplateLoc,
4423  RAngleLoc,
4424  TempTempParm,
4425  Converted,
4426  QualifierLoc);
4427  if (TName.isNull())
4428  return TemplateArgumentLoc();
4429 
4430  return TemplateArgumentLoc(TemplateArgument(TName),
4431  TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4432  TempTempParm->getDefaultArgument().getTemplateNameLoc());
4433 }
4434 
4435 /// Convert a template-argument that we parsed as a type into a template, if
4436 /// possible. C++ permits injected-class-names to perform dual service as
4437 /// template template arguments and as template type arguments.
4439  // Extract and step over any surrounding nested-name-specifier.
4440  NestedNameSpecifierLoc QualLoc;
4441  if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4442  if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4443  return TemplateArgumentLoc();
4444 
4445  QualLoc = ETLoc.getQualifierLoc();
4446  TLoc = ETLoc.getNamedTypeLoc();
4447  }
4448 
4449  // If this type was written as an injected-class-name, it can be used as a
4450  // template template argument.
4451  if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4452  return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4453  QualLoc, InjLoc.getNameLoc());
4454 
4455  // If this type was written as an injected-class-name, it may have been
4456  // converted to a RecordType during instantiation. If the RecordType is
4457  // *not* wrapped in a TemplateSpecializationType and denotes a class
4458  // template specialization, it must have come from an injected-class-name.
4459  if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4460  if (auto *CTSD =
4461  dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4462  return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4463  QualLoc, RecLoc.getNameLoc());
4464 
4465  return TemplateArgumentLoc();
4466 }
4467 
4468 /// \brief Check that the given template argument corresponds to the given
4469 /// template parameter.
4470 ///
4471 /// \param Param The template parameter against which the argument will be
4472 /// checked.
4473 ///
4474 /// \param Arg The template argument, which may be updated due to conversions.
4475 ///
4476 /// \param Template The template in which the template argument resides.
4477 ///
4478 /// \param TemplateLoc The location of the template name for the template
4479 /// whose argument list we're matching.
4480 ///
4481 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4482 /// the template argument list.
4483 ///
4484 /// \param ArgumentPackIndex The index into the argument pack where this
4485 /// argument will be placed. Only valid if the parameter is a parameter pack.
4486 ///
4487 /// \param Converted The checked, converted argument will be added to the
4488 /// end of this small vector.
4489 ///
4490 /// \param CTAK Describes how we arrived at this particular template argument:
4491 /// explicitly written, deduced, etc.
4492 ///
4493 /// \returns true on error, false otherwise.
4495  TemplateArgumentLoc &Arg,
4496  NamedDecl *Template,
4497  SourceLocation TemplateLoc,
4498  SourceLocation RAngleLoc,
4499  unsigned ArgumentPackIndex,
4502  // Check template type parameters.
4503  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4504  return CheckTemplateTypeArgument(TTP, Arg, Converted);
4505 
4506  // Check non-type template parameters.
4507  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4508  // Do substitution on the type of the non-type template parameter
4509  // with the template arguments we've seen thus far. But if the
4510  // template has a dependent context then we cannot substitute yet.
4511  QualType NTTPType = NTTP->getType();
4512  if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4513  NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4514 
4515  if (NTTPType->isDependentType() &&
4516  !isa<TemplateTemplateParmDecl>(Template) &&
4517  !Template->getDeclContext()->isDependentContext()) {
4518  // Do substitution on the type of the non-type template parameter.
4519  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4520  NTTP, Converted,
4521  SourceRange(TemplateLoc, RAngleLoc));
4522  if (Inst.isInvalid())
4523  return true;
4524 
4526  Converted);
4527  NTTPType = SubstType(NTTPType,
4528  MultiLevelTemplateArgumentList(TemplateArgs),
4529  NTTP->getLocation(),
4530  NTTP->getDeclName());
4531  // If that worked, check the non-type template parameter type
4532  // for validity.
4533  if (!NTTPType.isNull())
4534  NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4535  NTTP->getLocation());
4536  if (NTTPType.isNull())
4537  return true;
4538  }
4539 
4540  switch (Arg.getArgument().getKind()) {
4542  llvm_unreachable("Should never see a NULL template argument here");
4543 
4545  TemplateArgument Result;
4546  ExprResult Res =
4547  CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4548  Result, CTAK);
4549  if (Res.isInvalid())
4550  return true;
4551 
4552  // If the resulting expression is new, then use it in place of the
4553  // old expression in the template argument.
4554  if (Res.get() != Arg.getArgument().getAsExpr()) {
4555  TemplateArgument TA(Res.get());
4556  Arg = TemplateArgumentLoc(TA, Res.get());
4557  }
4558 
4559  Converted.push_back(Result);
4560  break;
4561  }
4562 
4566  // We've already checked this template argument, so just copy
4567  // it to the list of converted arguments.
4568  Converted.push_back(Arg.getArgument());
4569  break;
4570 
4573  // We were given a template template argument. It may not be ill-formed;
4574  // see below.
4575  if (DependentTemplateName *DTN
4578  // We have a template argument such as \c T::template X, which we
4579  // parsed as a template template argument. However, since we now
4580  // know that we need a non-type template argument, convert this
4581  // template name into an expression.
4582 
4583  DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4584  Arg.getTemplateNameLoc());
4585 
4586  CXXScopeSpec SS;
4587  SS.Adopt(Arg.getTemplateQualifierLoc());
4588  // FIXME: the template-template arg was a DependentTemplateName,
4589  // so it was provided with a template keyword. However, its source
4590  // location is not stored in the template argument structure.
4591  SourceLocation TemplateKWLoc;
4593  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4594  nullptr);
4595 
4596  // If we parsed the template argument as a pack expansion, create a
4597  // pack expansion expression.
4599  E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4600  if (E.isInvalid())
4601  return true;
4602  }
4603 
4604  TemplateArgument Result;
4605  E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4606  if (E.isInvalid())
4607  return true;
4608 
4609  Converted.push_back(Result);
4610  break;
4611  }
4612 
4613  // We have a template argument that actually does refer to a class
4614  // template, alias template, or template template parameter, and
4615  // therefore cannot be a non-type template argument.
4616  Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4617  << Arg.getSourceRange();
4618 
4619  Diag(Param->getLocation(), diag::note_template_param_here);
4620  return true;
4621 
4622  case TemplateArgument::Type: {
4623  // We have a non-type template parameter but the template
4624  // argument is a type.
4625 
4626  // C++ [temp.arg]p2:
4627  // In a template-argument, an ambiguity between a type-id and
4628  // an expression is resolved to a type-id, regardless of the
4629  // form of the corresponding template-parameter.
4630  //
4631  // We warn specifically about this case, since it can be rather
4632  // confusing for users.
4633  QualType T = Arg.getArgument().getAsType();
4634  SourceRange SR = Arg.getSourceRange();
4635  if (T->isFunctionType())
4636  Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4637  else
4638  Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4639  Diag(Param->getLocation(), diag::note_template_param_here);
4640  return true;
4641  }
4642 
4644  llvm_unreachable("Caller must expand template argument packs");
4645  }
4646 
4647  return false;
4648  }
4649 
4650 
4651  // Check template template parameters.
4652  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4653 
4654  // Substitute into the template parameter list of the template
4655  // template parameter, since previously-supplied template arguments
4656  // may appear within the template template parameter.
4657  {
4658  // Set up a template instantiation context.
4660  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4661  TempParm, Converted,
4662  SourceRange(TemplateLoc, RAngleLoc));
4663  if (Inst.isInvalid())
4664  return true;
4665 
4666  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4667  TempParm = cast_or_null<TemplateTemplateParmDecl>(
4668  SubstDecl(TempParm, CurContext,
4669  MultiLevelTemplateArgumentList(TemplateArgs)));
4670  if (!TempParm)
4671  return true;
4672  }
4673 
4674  // C++1z [temp.local]p1: (DR1004)
4675  // When [the injected-class-name] is used [...] as a template-argument for
4676  // a template template-parameter [...] it refers to the class template
4677  // itself.
4678  if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4680  Arg.getTypeSourceInfo()->getTypeLoc());
4681  if (!ConvertedArg.getArgument().isNull())
4682  Arg = ConvertedArg;
4683  }
4684 
4685  switch (Arg.getArgument().getKind()) {
4687  llvm_unreachable("Should never see a NULL template argument here");
4688 
4691  if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4692  return true;
4693 
4694  Converted.push_back(Arg.getArgument());
4695  break;
4696 
4699  // We have a template template parameter but the template
4700  // argument does not refer to a template.
4701  Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4702  << getLangOpts().CPlusPlus11;
4703  return true;
4704 
4706  llvm_unreachable("Declaration argument with template template parameter");
4708  llvm_unreachable("Integral argument with template template parameter");
4710  llvm_unreachable("Null pointer argument with template template parameter");
4711 
4713  llvm_unreachable("Caller must expand template argument packs");
4714  }
4715 
4716  return false;
4717 }
4718 
4719 /// \brief Diagnose an arity mismatch in the
4720 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4721  SourceLocation TemplateLoc,
4722  TemplateArgumentListInfo &TemplateArgs) {
4723  TemplateParameterList *Params = Template->getTemplateParameters();
4724  unsigned NumParams = Params->size();
4725  unsigned NumArgs = TemplateArgs.size();
4726 
4727  SourceRange Range;
4728  if (NumArgs > NumParams)
4729  Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4730  TemplateArgs.getRAngleLoc());
4731  S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4732  << (NumArgs > NumParams)
4733  << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4734  << Template << Range;
4735  S.Diag(Template->getLocation(), diag::note_template_decl_here)
4736  << Params->getSourceRange();
4737  return true;
4738 }
4739 
4740 /// \brief Check whether the template parameter is a pack expansion, and if so,
4741 /// determine the number of parameters produced by that expansion. For instance:
4742 ///
4743 /// \code
4744 /// template<typename ...Ts> struct A {
4745 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4746 /// };
4747 /// \endcode
4748 ///
4749 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4750 /// is not a pack expansion, so returns an empty Optional.
4752  if (NonTypeTemplateParmDecl *NTTP
4753  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4754  if (NTTP->isExpandedParameterPack())
4755  return NTTP->getNumExpansionTypes();
4756  }
4757 
4758  if (TemplateTemplateParmDecl *TTP
4759  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4760  if (TTP->isExpandedParameterPack())
4761  return TTP->getNumExpansionTemplateParameters();
4762  }
4763 
4764  return None;
4765 }
4766 
4767 /// Diagnose a missing template argument.
4768 template<typename TemplateParmDecl>
4770  TemplateDecl *TD,
4771  const TemplateParmDecl *D,
4772  TemplateArgumentListInfo &Args) {
4773  // Dig out the most recent declaration of the template parameter; there may be
4774  // declarations of the template that are more recent than TD.
4775  D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4776  ->getTemplateParameters()
4777  ->getParam(D->getIndex()));
4778 
4779  // If there's a default argument that's not visible, diagnose that we're
4780  // missing a module import.
4782  if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4783  S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4784  D->getDefaultArgumentLoc(), Modules,
4786  /*Recover*/true);
4787  return true;
4788  }
4789 
4790  // FIXME: If there's a more recent default argument that *is* visible,
4791  // diagnose that it was declared too late.
4792 
4793  return diagnoseArityMismatch(S, TD, Loc, Args);
4794 }
4795 
4796 /// \brief Check that the given template argument list is well-formed
4797 /// for specializing the given template.
4799  TemplateDecl *Template, SourceLocation TemplateLoc,
4800  TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4802  bool UpdateArgsWithConversions) {
4803  // Make a copy of the template arguments for processing. Only make the
4804  // changes at the end when successful in matching the arguments to the
4805  // template.
4806  TemplateArgumentListInfo NewArgs = TemplateArgs;
4807 
4808  // Make sure we get the template parameter list from the most
4809  // recentdeclaration, since that is the only one that has is guaranteed to
4810  // have all the default template argument information.
4811  TemplateParameterList *Params =
4812  cast<TemplateDecl>(Template->getMostRecentDecl())
4813  ->getTemplateParameters();
4814 
4815  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4816 
4817  // C++ [temp.arg]p1:
4818  // [...] The type and form of each template-argument specified in
4819  // a template-id shall match the type and form specified for the
4820  // corresponding parameter declared by the template in its
4821  // template-parameter-list.
4822  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4823  SmallVector<TemplateArgument, 2> ArgumentPack;
4824  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4825  LocalInstantiationScope InstScope(*this, true);
4826  for (TemplateParameterList::iterator Param = Params->begin(),
4827  ParamEnd = Params->end();
4828  Param != ParamEnd; /* increment in loop */) {
4829  // If we have an expanded parameter pack, make sure we don't have too
4830  // many arguments.
4831  if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4832  if (*Expansions == ArgumentPack.size()) {
4833  // We're done with this parameter pack. Pack up its arguments and add
4834  // them to the list.
4835  Converted.push_back(
4836  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4837  ArgumentPack.clear();
4838 
4839  // This argument is assigned to the next parameter.
4840  ++Param;
4841  continue;
4842  } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4843  // Not enough arguments for this parameter pack.
4844  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4845  << false
4846  << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4847  << Template;
4848  Diag(Template->getLocation(), diag::note_template_decl_here)
4849  << Params->getSourceRange();
4850  return true;
4851  }
4852  }
4853 
4854  if (ArgIdx < NumArgs) {
4855  // Check the template argument we were given.
4856  if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4857  TemplateLoc, RAngleLoc,
4858  ArgumentPack.size(), Converted))
4859  return true;
4860 
4861  bool PackExpansionIntoNonPack =
4862  NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4863  (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4864  if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4865  // Core issue 1430: we have a pack expansion as an argument to an
4866  // alias template, and it's not part of a parameter pack. This
4867  // can't be canonicalized, so reject it now.
4868  Diag(NewArgs[ArgIdx].getLocation(),
4869  diag::err_alias_template_expansion_into_fixed_list)
4870  << NewArgs[ArgIdx].getSourceRange();
4871  Diag((*Param)->getLocation(), diag::note_template_param_here);
4872  return true;
4873  }
4874 
4875  // We're now done with this argument.
4876  ++ArgIdx;
4877 
4878  if ((*Param)->isTemplateParameterPack()) {
4879  // The template parameter was a template parameter pack, so take the
4880  // deduced argument and place it on the argument pack. Note that we
4881  // stay on the same template parameter so that we can deduce more
4882  // arguments.
4883  ArgumentPack.push_back(Converted.pop_back_val());
4884  } else {
4885  // Move to the next template parameter.
4886  ++Param;
4887  }
4888 
4889  // If we just saw a pack expansion into a non-pack, then directly convert
4890  // the remaining arguments, because we don't know what parameters they'll
4891  // match up with.
4892  if (PackExpansionIntoNonPack) {
4893  if (!ArgumentPack.empty()) {
4894  // If we were part way through filling in an expanded parameter pack,
4895  // fall back to just producing individual arguments.
4896  Converted.insert(Converted.end(),
4897  ArgumentPack.begin(), ArgumentPack.end());
4898  ArgumentPack.clear();
4899  }
4900 
4901  while (ArgIdx < NumArgs) {
4902  Converted.push_back(NewArgs[ArgIdx].getArgument());
4903  ++ArgIdx;
4904  }
4905 
4906  return false;
4907  }
4908 
4909  continue;
4910  }
4911 
4912  // If we're checking a partial template argument list, we're done.
4913  if (PartialTemplateArgs) {
4914  if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4915  Converted.push_back(
4916  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4917 
4918  return false;
4919  }
4920 
4921  // If we have a template parameter pack with no more corresponding
4922  // arguments, just break out now and we'll fill in the argument pack below.
4923  if ((*Param)->isTemplateParameterPack()) {
4924  assert(!getExpandedPackSize(*Param) &&
4925  "Should have dealt with this already");
4926 
4927  // A non-expanded parameter pack before the end of the parameter list
4928  // only occurs for an ill-formed template parameter list, unless we've
4929  // got a partial argument list for a function template, so just bail out.
4930  if (Param + 1 != ParamEnd)
4931  return true;
4932 
4933  Converted.push_back(
4934  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4935  ArgumentPack.clear();
4936 
4937  ++Param;
4938  continue;
4939  }
4940 
4941  // Check whether we have a default argument.
4942  TemplateArgumentLoc Arg;
4943 
4944  // Retrieve the default template argument from the template
4945  // parameter. For each kind of template parameter, we substitute the
4946  // template arguments provided thus far and any "outer" template arguments
4947  // (when the template parameter was part of a nested template) into
4948  // the default argument.
4949  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
4950  if (!hasVisibleDefaultArgument(TTP))
4951  return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4952  NewArgs);
4953 
4955  Template,
4956  TemplateLoc,
4957  RAngleLoc,
4958  TTP,
4959  Converted);
4960  if (!ArgType)
4961  return true;
4962 
4963  Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4964  ArgType);
4965  } else if (NonTypeTemplateParmDecl *NTTP
4966  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
4967  if (!hasVisibleDefaultArgument(NTTP))
4968  return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4969  NewArgs);
4970 
4971  ExprResult E = SubstDefaultTemplateArgument(*this, Template,
4972  TemplateLoc,
4973  RAngleLoc,
4974  NTTP,
4975  Converted);
4976  if (E.isInvalid())
4977  return true;
4978 
4979  Expr *Ex = E.getAs<Expr>();
4980  Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4981  } else {
4982  TemplateTemplateParmDecl *TempParm
4983  = cast<TemplateTemplateParmDecl>(*Param);
4984 
4985  if (!hasVisibleDefaultArgument(TempParm))
4986  return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4987  NewArgs);
4988 
4989  NestedNameSpecifierLoc QualifierLoc;
4990  TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
4991  TemplateLoc,
4992  RAngleLoc,
4993  TempParm,
4994  Converted,
4995  QualifierLoc);
4996  if (Name.isNull())
4997  return true;
4998 
4999  Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5000  TempParm->getDefaultArgument().getTemplateNameLoc());
5001  }
5002 
5003  // Introduce an instantiation record that describes where we are using
5004  // the default template argument. We're not actually instantiating a
5005  // template here, we just create this object to put a note into the
5006  // context stack.
5007  InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5008  SourceRange(TemplateLoc, RAngleLoc));
5009  if (Inst.isInvalid())
5010  return true;
5011 
5012  // Check the default template argument.
5013  if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5014  RAngleLoc, 0, Converted))
5015  return true;
5016 
5017  // Core issue 150 (assumed resolution): if this is a template template
5018  // parameter, keep track of the default template arguments from the
5019  // template definition.
5020  if (isTemplateTemplateParameter)
5021  NewArgs.addArgument(Arg);
5022 
5023  // Move to the next template parameter and argument.
5024  ++Param;
5025  ++ArgIdx;
5026  }
5027 
5028  // If we're performing a partial argument substitution, allow any trailing
5029  // pack expansions; they might be empty. This can happen even if
5030  // PartialTemplateArgs is false (the list of arguments is complete but
5031  // still dependent).
5032  if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5033  CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5034  while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5035  Converted.push_back(NewArgs[ArgIdx++].getArgument());
5036  }
5037 
5038  // If we have any leftover arguments, then there were too many arguments.
5039  // Complain and fail.
5040  if (ArgIdx < NumArgs)
5041  return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5042 
5043  // No problems found with the new argument list, propagate changes back
5044  // to caller.
5045  if (UpdateArgsWithConversions)
5046  TemplateArgs = std::move(NewArgs);
5047 
5048  return false;
5049 }
5050 
5051 namespace {
5052  class UnnamedLocalNoLinkageFinder
5053  : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5054  {
5055  Sema &S;
5056  SourceRange SR;
5057 
5059 
5060  public:
5061  UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5062 
5063  bool Visit(QualType T) {
5064  return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5065  }
5066 
5067 #define TYPE(Class, Parent) \
5068  bool Visit##Class##Type(const Class##Type *);
5069 #define ABSTRACT_TYPE(Class, Parent) \
5070  bool Visit##Class##Type(const Class##Type *) { return false; }
5071 #define NON_CANONICAL_TYPE(Class, Parent) \
5072  bool Visit##Class##Type(const Class##Type *) { return false; }
5073 #include "clang/AST/TypeNodes.def"
5074 
5075  bool VisitTagDecl(const TagDecl *Tag);
5076  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5077  };
5078 } // end anonymous namespace
5079 
5080 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5081  return false;
5082 }
5083 
5084 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5085  return Visit(T->getElementType());
5086 }
5087 
5088 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5089  return Visit(T->getPointeeType());
5090 }
5091 
5092 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5093  const BlockPointerType* T) {
5094  return Visit(T->getPointeeType());
5095 }
5096 
5097 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5098  const LValueReferenceType* T) {
5099  return Visit(T->getPointeeType());
5100 }
5101 
5102 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5103  const RValueReferenceType* T) {
5104  return Visit(T->getPointeeType());
5105 }
5106 
5107 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5108  const MemberPointerType* T) {
5109  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5110 }
5111 
5112 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5113  const ConstantArrayType* T) {
5114  return Visit(T->getElementType());
5115 }
5116 
5117 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5118  const IncompleteArrayType* T) {
5119  return Visit(T->getElementType());
5120 }
5121 
5122 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5123  const VariableArrayType* T) {
5124  return Visit(T->getElementType());
5125 }
5126 
5127 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5128  const DependentSizedArrayType* T) {
5129  return Visit(T->getElementType());
5130 }
5131 
5132 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5133  const DependentSizedExtVectorType* T) {
5134  return Visit(T->getElementType());
5135 }
5136 
5137 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5138  const DependentAddressSpaceType *T) {
5139  return Visit(T->getPointeeType());
5140 }
5141 
5142 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5143  return Visit(T->getElementType());
5144 }
5145 
5146 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5147  return Visit(T->getElementType());
5148 }
5149 
5150 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5151  const FunctionProtoType* T) {
5152  for (const auto &A : T->param_types()) {
5153  if (Visit(A))
5154  return true;
5155  }
5156 
5157  return Visit(T->getReturnType());
5158 }
5159 
5160 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5161  const FunctionNoProtoType* T) {
5162  return Visit(T->getReturnType());
5163 }
5164 
5165 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5166  const UnresolvedUsingType*) {
5167  return false;
5168 }
5169 
5170 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5171  return false;
5172 }
5173 
5174 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5175  return Visit(T->getUnderlyingType());
5176 }
5177 
5178 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5179  return false;
5180 }
5181 
5182 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5183  const UnaryTransformType*) {
5184  return false;
5185 }
5186 
5187 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5188  return Visit(T->getDeducedType());
5189 }
5190 
5191 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5193  return Visit(T->getDeducedType());
5194 }
5195 
5196 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5197  return VisitTagDecl(T->getDecl());
5198 }
5199 
5200 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5201  return VisitTagDecl(T->getDecl());
5202 }
5203 
5204 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5205  const TemplateTypeParmType*) {
5206  return false;
5207 }
5208 
5209 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5211  return false;
5212 }
5213 
5214 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5215  const TemplateSpecializationType*) {
5216  return false;
5217 }
5218 
5219 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5220  const InjectedClassNameType* T) {
5221  return VisitTagDecl(T->getDecl());
5222 }
5223 
5224 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5225  const DependentNameType* T) {
5226  return VisitNestedNameSpecifier(T->getQualifier());
5227 }
5228 
5229 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5231  return VisitNestedNameSpecifier(T->getQualifier());
5232 }
5233 
5234 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5235  const PackExpansionType* T) {
5236  return Visit(T->getPattern());
5237 }
5238 
5239 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5240  return false;
5241 }
5242 
5243 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5244  const ObjCInterfaceType *) {
5245  return false;
5246 }
5247 
5248 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5249  const ObjCObjectPointerType *) {
5250  return false;
5251 }
5252 
5253 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5254  return Visit(T->getValueType());
5255 }
5256 
5257 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5258  return false;
5259 }
5260 
5261 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5262  if (Tag->getDeclContext()->isFunctionOrMethod()) {
5263  S.Diag(SR.getBegin(),
5264  S.getLangOpts().CPlusPlus11 ?
5265  diag::warn_cxx98_compat_template_arg_local_type :
5266  diag::ext_template_arg_local_type)
5267  << S.Context.getTypeDeclType(Tag) << SR;
5268  return true;
5269  }
5270 
5271  if (!Tag->hasNameForLinkage()) {
5272  S.Diag(SR.getBegin(),
5273  S.getLangOpts().CPlusPlus11 ?
5274  diag::warn_cxx98_compat_template_arg_unnamed_type :
5275  diag::ext_template_arg_unnamed_type) << SR;
5276  S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5277  return true;
5278  }
5279 
5280  return false;
5281 }
5282 
5283 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5284  NestedNameSpecifier *NNS) {
5285  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5286  return true;
5287 
5288  switch (NNS->getKind()) {
5294  return false;
5295 
5298  return Visit(QualType(NNS->getAsType(), 0));
5299  }
5300  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5301 }
5302 
5303 /// \brief Check a template argument against its corresponding
5304 /// template type parameter.
5305 ///
5306 /// This routine implements the semantics of C++ [temp.arg.type]. It
5307 /// returns true if an error occurred, and false otherwise.
5309  TypeSourceInfo *ArgInfo) {
5310  assert(ArgInfo && "invalid TypeSourceInfo");
5311  QualType Arg = ArgInfo->getType();
5312  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5313 
5314  if (Arg->isVariablyModifiedType()) {
5315  return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5316  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5317  return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5318  }
5319 
5320  // C++03 [temp.arg.type]p2:
5321  // A local type, a type with no linkage, an unnamed type or a type
5322  // compounded from any of these types shall not be used as a
5323  // template-argument for a template type-parameter.
5324  //
5325  // C++11 allows these, and even in C++03 we allow them as an extension with
5326  // a warning.
5327  if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5328  UnnamedLocalNoLinkageFinder Finder(*this, SR);
5329  (void)Finder.Visit(Context.getCanonicalType(Arg));
5330  }
5331 
5332  return false;
5333 }
5334 
5339 };
5340 
5341 /// \brief Determine whether the given template argument is a null pointer
5342 /// value of the appropriate type.
5343 static NullPointerValueKind
5345  QualType ParamType, Expr *Arg,
5346  Decl *Entity = nullptr) {
5347  if (Arg->isValueDependent() || Arg->isTypeDependent())
5348  return NPV_NotNullPointer;
5349 
5350  // dllimport'd entities aren't constant but are available inside of template
5351  // arguments.
5352  if (Entity && Entity->hasAttr<DLLImportAttr>())
5353  return NPV_NotNullPointer;
5354 
5355  if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5356  llvm_unreachable(
5357  "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5358 
5359  if (!S.getLangOpts().CPlusPlus11)
5360  return NPV_NotNullPointer;
5361 
5362  // Determine whether we have a constant expression.
5364  if (ArgRV.isInvalid())
5365  return NPV_Error;
5366  Arg = ArgRV.get();
5367 
5368  Expr::EvalResult EvalResult;
5370  EvalResult.Diag = &Notes;
5371  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5372  EvalResult.HasSideEffects) {
5373  SourceLocation DiagLoc = Arg->getExprLoc();
5374 
5375  // If our only note is the usual "invalid subexpression" note, just point
5376  // the caret at its location rather than producing an essentially
5377  // redundant note.
5378  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5379  diag::note_invalid_subexpr_in_const_expr) {
5380  DiagLoc = Notes[0].first;
5381  Notes.clear();
5382  }
5383 
5384  S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5385  << Arg->getType() << Arg->getSourceRange();
5386  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5387  S.Diag(Notes[I].first, Notes[I].second);
5388 
5389  S.Diag(Param->getLocation(), diag::note_template_param_here);
5390  return NPV_Error;
5391  }
5392 
5393  // C++11 [temp.arg.nontype]p1:
5394  // - an address constant expression of type std::nullptr_t
5395  if (Arg->getType()->isNullPtrType())
5396  return NPV_NullPointer;
5397 
5398  // - a constant expression that evaluates to a null pointer value (4.10); or
5399  // - a constant expression that evaluates to a null member pointer value
5400  // (4.11); or
5401  if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5402  (EvalResult.Val.isMemberPointer() &&
5403  !EvalResult.Val.getMemberPointerDecl())) {
5404  // If our expression has an appropriate type, we've succeeded.
5405  bool ObjCLifetimeConversion;
5406  if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5407  S.IsQualificationConversion(Arg->getType(), ParamType, false,
5408  ObjCLifetimeConversion))
5409  return NPV_NullPointer;
5410 
5411  // The types didn't match, but we know we got a null pointer; complain,
5412  // then recover as if the types were correct.
5413  S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5414  << Arg->getType() << ParamType << Arg->getSourceRange();
5415  S.Diag(Param->getLocation(), diag::note_template_param_here);
5416  return NPV_NullPointer;
5417  }
5418 
5419  // If we don't have a null pointer value, but we do have a NULL pointer
5420  // constant, suggest a cast to the appropriate type.
5422  std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5423  S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5424  << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5426  ")");
5427  S.Diag(Param->getLocation(), diag::note_template_param_here);
5428  return NPV_NullPointer;
5429  }
5430 
5431  // FIXME: If we ever want to support general, address-constant expressions
5432  // as non-type template arguments, we should return the ExprResult here to
5433  // be interpreted by the caller.
5434  return NPV_NotNullPointer;
5435 }
5436 
5437 /// \brief Checks whether the given template argument is compatible with its
5438 /// template parameter.
5440  Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5441  Expr *Arg, QualType ArgType) {
5442  bool ObjCLifetimeConversion;
5443  if (ParamType->isPointerType() &&
5444  !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5445  S.IsQualificationConversion(ArgType, ParamType, false,
5446  ObjCLifetimeConversion)) {
5447  // For pointer-to-object types, qualification conversions are
5448  // permitted.
5449  } else {
5450  if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5451  if (!ParamRef->getPointeeType()->isFunctionType()) {
5452  // C++ [temp.arg.nontype]p5b3:
5453  // For a non-type template-parameter of type reference to
5454  // object, no conversions apply. The type referred to by the
5455  // reference may be more cv-qualified than the (otherwise
5456  // identical) type of the template- argument. The
5457  // template-parameter is bound directly to the
5458  // template-argument, which shall be an lvalue.
5459 
5460  // FIXME: Other qualifiers?
5461  unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5462  unsigned ArgQuals = ArgType.getCVRQualifiers();
5463 
5464  if ((ParamQuals | ArgQuals) != ParamQuals) {
5465  S.Diag(Arg->getLocStart(),
5466  diag::err_template_arg_ref_bind_ignores_quals)
5467  << ParamType << Arg->getType() << Arg->getSourceRange();
5468  S.Diag(Param->getLocation(), diag::note_template_param_here);
5469  return true;
5470  }
5471  }
5472  }
5473 
5474  // At this point, the template argument refers to an object or
5475  // function with external linkage. We now need to check whether the
5476  // argument and parameter types are compatible.
5477  if (!S.Context.hasSameUnqualifiedType(ArgType,
5478  ParamType.getNonReferenceType())) {
5479  // We can't perform this conversion or binding.
5480  if (ParamType->isReferenceType())
5481  S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5482  << ParamType << ArgIn->getType() << Arg->getSourceRange();
5483  else
5484  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5485  << ArgIn->getType() << ParamType << Arg->getSourceRange();
5486  S.Diag(Param->getLocation(), diag::note_template_param_here);
5487  return true;
5488  }
5489  }
5490 
5491  return false;
5492 }
5493 
5494 /// \brief Checks whether the given template argument is the address
5495 /// of an object or function according to C++ [temp.arg.nontype]p1.
5496 static bool
5498  NonTypeTemplateParmDecl *Param,
5499  QualType ParamType,
5500  Expr *ArgIn,
5501  TemplateArgument &Converted) {
5502  bool Invalid = false;
5503  Expr *Arg = ArgIn;
5504  QualType ArgType = Arg->getType();
5505 
5506  bool AddressTaken = false;
5507  SourceLocation AddrOpLoc;
5508  if (S.getLangOpts().MicrosoftExt) {
5509  // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5510  // dereference and address-of operators.
5511  Arg = Arg->IgnoreParenCasts();
5512 
5513  bool ExtWarnMSTemplateArg = false;
5514  UnaryOperatorKind FirstOpKind;
5515  SourceLocation FirstOpLoc;
5516  while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5517  UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5518  if (UnOpKind == UO_Deref)
5519  ExtWarnMSTemplateArg = true;
5520  if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5521  Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5522  if (!AddrOpLoc.isValid()) {
5523  FirstOpKind = UnOpKind;
5524  FirstOpLoc = UnOp->getOperatorLoc();
5525  }
5526  } else
5527  break;
5528  }
5529  if (FirstOpLoc.isValid()) {
5530  if (ExtWarnMSTemplateArg)
5531  S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5532  << ArgIn->getSourceRange();
5533 
5534  if (FirstOpKind == UO_AddrOf)
5535  AddressTaken = true;
5536  else if (Arg->getType()->isPointerType()) {
5537  // We cannot let pointers get dereferenced here, that is obviously not a
5538  // constant expression.
5539  assert(FirstOpKind == UO_Deref);
5540  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5541  << Arg->getSourceRange();
5542  }
5543  }
5544  } else {
5545  // See through any implicit casts we added to fix the type.
5546  Arg = Arg->IgnoreImpCasts();
5547 
5548  // C++ [temp.arg.nontype]p1:
5549  //
5550  // A template-argument for a non-type, non-template
5551  // template-parameter shall be one of: [...]
5552  //
5553  // -- the address of an object or function with external
5554  // linkage, including function templates and function
5555  // template-ids but excluding non-static class members,
5556  // expressed as & id-expression where the & is optional if
5557  // the name refers to a function or array, or if the
5558  // corresponding template-parameter is a reference; or
5559 
5560  // In C++98/03 mode, give an extension warning on any extra parentheses.
5561  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5562  bool ExtraParens = false;
5563  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5564  if (!Invalid && !ExtraParens) {
5565  S.Diag(Arg->getLocStart(),
5566  S.getLangOpts().CPlusPlus11
5567  ? diag::warn_cxx98_compat_template_arg_extra_parens
5568  : diag::ext_template_arg_extra_parens)
5569  << Arg->getSourceRange();
5570  ExtraParens = true;
5571  }
5572 
5573  Arg = Parens->getSubExpr();
5574  }
5575 
5576  while (SubstNonTypeTemplateParmExpr *subst =
5577  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5578  Arg = subst->getReplacement()->IgnoreImpCasts();
5579 
5580  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5581  if (UnOp->getOpcode() == UO_AddrOf) {
5582  Arg = UnOp->getSubExpr();
5583  AddressTaken = true;
5584  AddrOpLoc = UnOp->getOperatorLoc();
5585  }
5586  }
5587 
5588  while (SubstNonTypeTemplateParmExpr *subst =
5589  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5590  Arg = subst->getReplacement()->IgnoreImpCasts();
5591  }
5592 
5593  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5594  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5595 
5596  // If our parameter has pointer type, check for a null template value.
5597  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5598  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5599  Entity)) {
5600  case NPV_NullPointer:
5601  S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5602  Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5603  /*isNullPtr=*/true);
5604  return false;
5605 
5606  case NPV_Error:
5607  return true;
5608 
5609  case NPV_NotNullPointer:
5610  break;
5611  }
5612  }
5613 
5614  // Stop checking the precise nature of the argument if it is value dependent,
5615  // it should be checked when instantiated.
5616  if (Arg->isValueDependent()) {
5617  Converted = TemplateArgument(ArgIn);
5618  return false;
5619  }
5620 
5621  if (isa<CXXUuidofExpr>(Arg)) {
5622  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5623  ArgIn, Arg, ArgType))
5624  return true;
5625 
5626  Converted = TemplateArgument(ArgIn);
5627  return false;
5628  }
5629 
5630  if (!DRE) {
5631  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5632  << Arg->getSourceRange();
5633  S.Diag(Param->getLocation(), diag::note_template_param_here);
5634  return true;
5635  }
5636 
5637  // Cannot refer to non-static data members
5638  if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5639  S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5640  << Entity << Arg->getSourceRange();
5641  S.Diag(Param->getLocation(), diag::note_template_param_here);
5642  return true;
5643  }
5644 
5645  // Cannot refer to non-static member functions
5646  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5647  if (!Method->isStatic()) {
5648  S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5649  << Method << Arg->getSourceRange();
5650  S.Diag(Param->getLocation(), diag::note_template_param_here);
5651  return true;
5652  }
5653  }
5654 
5655  FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5656  VarDecl *Var = dyn_cast<VarDecl>(Entity);
5657 
5658  // A non-type template argument must refer to an object or function.
5659  if (!Func && !Var) {
5660  // We found something, but we don't know specifically what it is.
5661  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5662  << Arg->getSourceRange();
5663  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5664  return true;
5665  }
5666 
5667  // Address / reference template args must have external linkage in C++98.
5668  if (Entity->getFormalLinkage() == InternalLinkage) {
5669  S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5670  diag::warn_cxx98_compat_template_arg_object_internal :
5671  diag::ext_template_arg_object_internal)
5672  << !Func << Entity << Arg->getSourceRange();
5673  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5674  << !Func;
5675  } else if (!Entity->hasLinkage()) {
5676  S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5677  << !Func << Entity << Arg->getSourceRange();
5678  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5679  << !Func;
5680  return true;
5681  }
5682 
5683  if (Func) {
5684  // If the template parameter has pointer type, the function decays.
5685  if (ParamType->isPointerType() && !AddressTaken)
5686  ArgType = S.Context.getPointerType(Func->getType());
5687  else if (AddressTaken && ParamType->isReferenceType()) {
5688  // If we originally had an address-of operator, but the
5689  // parameter has reference type, complain and (if things look
5690  // like they will work) drop the address-of operator.
5691  if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5692  ParamType.getNonReferenceType())) {
5693  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5694  << ParamType;
5695  S.Diag(Param->getLocation(), diag::note_template_param_here);
5696  return true;
5697  }
5698 
5699  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5700  << ParamType
5701  << FixItHint::CreateRemoval(AddrOpLoc);
5702  S.Diag(Param->getLocation(), diag::note_template_param_here);
5703 
5704  ArgType = Func->getType();
5705  }
5706  } else {
5707  // A value of reference type is not an object.
5708  if (Var->getType()->isReferenceType()) {
5709  S.Diag(Arg->getLocStart(),
5710  diag::err_template_arg_reference_var)
5711  << Var->getType() << Arg->getSourceRange();
5712  S.Diag(Param->getLocation(), diag::note_template_param_here);
5713  return true;
5714  }
5715 
5716  // A template argument must have static storage duration.
5717  if (Var->getTLSKind()) {
5718  S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5719  << Arg->getSourceRange();
5720  S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5721  return true;
5722  }
5723 
5724  // If the template parameter has pointer type, we must have taken
5725  // the address of this object.
5726  if (ParamType->isReferenceType()) {
5727  if (AddressTaken) {
5728  // If we originally had an address-of operator, but the
5729  // parameter has reference type, complain and (if things look
5730  // like they will work) drop the address-of operator.
5731  if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5732  ParamType.getNonReferenceType())) {
5733  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5734  << ParamType;
5735  S.Diag(Param->getLocation(), diag::note_template_param_here);
5736  return true;
5737  }
5738 
5739  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5740  << ParamType
5741  << FixItHint::CreateRemoval(AddrOpLoc);
5742  S.Diag(Param->getLocation(), diag::note_template_param_here);
5743 
5744  ArgType = Var->getType();
5745  }
5746  } else if (!AddressTaken && ParamType->isPointerType()) {
5747  if (Var->getType()->isArrayType()) {
5748  // Array-to-pointer decay.
5749  ArgType = S.Context.getArrayDecayedType(Var->getType());
5750  } else {
5751  // If the template parameter has pointer type but the address of
5752  // this object was not taken, complain and (possibly) recover by
5753  // taking the address of the entity.
5754  ArgType = S.Context.getPointerType(Var->getType());
5755  if (!S.Context.