clang  10.0.0svn
SemaTemplate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
7 //
8 // This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
10 
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclFriend.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/TypeVisitor.h"
20 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/Template.h"
31 #include "llvm/ADT/SmallBitVector.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
34 
35 #include <iterator>
36 using namespace clang;
37 using namespace sema;
38 
39 // Exported for use by Parser.
42  unsigned N) {
43  if (!N) return SourceRange();
44  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45 }
46 
47 namespace clang {
48 /// [temp.constr.decl]p2: A template's associated constraints are
49 /// defined as a single constraint-expression derived from the introduced
50 /// constraint-expressions [ ... ].
51 ///
52 /// \param Params The template parameter list and optional requires-clause.
53 ///
54 /// \param FD The underlying templated function declaration for a function
55 /// template.
57  FunctionDecl *FD);
58 }
59 
61  FunctionDecl *FD) {
62  // FIXME: Concepts: collect additional introduced constraint-expressions
63  assert(!FD && "Cannot collect constraints from function declaration yet.");
64  return Params->getRequiresClause();
65 }
66 
67 /// Determine whether the declaration found is acceptable as the name
68 /// of a template and, if so, return that template declaration. Otherwise,
69 /// returns null.
70 ///
71 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
72 /// is true. In all other cases it will return a TemplateDecl (or null).
74  bool AllowFunctionTemplates,
75  bool AllowDependent) {
76  D = D->getUnderlyingDecl();
77 
78  if (isa<TemplateDecl>(D)) {
79  if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
80  return nullptr;
81 
82  return D;
83  }
84 
85  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
86  // C++ [temp.local]p1:
87  // Like normal (non-template) classes, class templates have an
88  // injected-class-name (Clause 9). The injected-class-name
89  // can be used with or without a template-argument-list. When
90  // it is used without a template-argument-list, it is
91  // equivalent to the injected-class-name followed by the
92  // template-parameters of the class template enclosed in
93  // <>. When it is used with a template-argument-list, it
94  // refers to the specified class template specialization,
95  // which could be the current specialization or another
96  // specialization.
97  if (Record->isInjectedClassName()) {
98  Record = cast<CXXRecordDecl>(Record->getDeclContext());
99  if (Record->getDescribedClassTemplate())
100  return Record->getDescribedClassTemplate();
101 
103  = dyn_cast<ClassTemplateSpecializationDecl>(Record))
104  return Spec->getSpecializedTemplate();
105  }
106 
107  return nullptr;
108  }
109 
110  // 'using Dependent::foo;' can resolve to a template name.
111  // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
112  // injected-class-name).
113  if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
114  return D;
115 
116  return nullptr;
117 }
118 
120  bool AllowFunctionTemplates,
121  bool AllowDependent) {
122  LookupResult::Filter filter = R.makeFilter();
123  while (filter.hasNext()) {
124  NamedDecl *Orig = filter.next();
125  if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
126  filter.erase();
127  }
128  filter.done();
129 }
130 
132  bool AllowFunctionTemplates,
133  bool AllowDependent,
134  bool AllowNonTemplateFunctions) {
135  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
136  if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
137  return true;
138  if (AllowNonTemplateFunctions &&
139  isa<FunctionDecl>((*I)->getUnderlyingDecl()))
140  return true;
141  }
142 
143  return false;
144 }
145 
147  CXXScopeSpec &SS,
148  bool hasTemplateKeyword,
149  const UnqualifiedId &Name,
150  ParsedType ObjectTypePtr,
151  bool EnteringContext,
152  TemplateTy &TemplateResult,
153  bool &MemberOfUnknownSpecialization) {
154  assert(getLangOpts().CPlusPlus && "No template names in C!");
155 
156  DeclarationName TName;
157  MemberOfUnknownSpecialization = false;
158 
159  switch (Name.getKind()) {
161  TName = DeclarationName(Name.Identifier);
162  break;
163 
165  TName = Context.DeclarationNames.getCXXOperatorName(
167  break;
168 
171  break;
172 
173  default:
174  return TNK_Non_template;
175  }
176 
177  QualType ObjectType = ObjectTypePtr.get();
178 
179  AssumedTemplateKind AssumedTemplate;
180  LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
181  if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
182  MemberOfUnknownSpecialization, SourceLocation(),
183  &AssumedTemplate))
184  return TNK_Non_template;
185 
186  if (AssumedTemplate != AssumedTemplateKind::None) {
187  TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
188  // Let the parser know whether we found nothing or found functions; if we
189  // found nothing, we want to more carefully check whether this is actually
190  // a function template name versus some other kind of undeclared identifier.
191  return AssumedTemplate == AssumedTemplateKind::FoundNothing
194  }
195 
196  if (R.empty())
197  return TNK_Non_template;
198 
199  NamedDecl *D = nullptr;
200  if (R.isAmbiguous()) {
201  // If we got an ambiguity involving a non-function template, treat this
202  // as a template name, and pick an arbitrary template for error recovery.
203  bool AnyFunctionTemplates = false;
204  for (NamedDecl *FoundD : R) {
205  if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
206  if (isa<FunctionTemplateDecl>(FoundTemplate))
207  AnyFunctionTemplates = true;
208  else {
209  D = FoundTemplate;
210  break;
211  }
212  }
213  }
214 
215  // If we didn't find any templates at all, this isn't a template name.
216  // Leave the ambiguity for a later lookup to diagnose.
217  if (!D && !AnyFunctionTemplates) {
218  R.suppressDiagnostics();
219  return TNK_Non_template;
220  }
221 
222  // If the only templates were function templates, filter out the rest.
223  // We'll diagnose the ambiguity later.
224  if (!D)
225  FilterAcceptableTemplateNames(R);
226  }
227 
228  // At this point, we have either picked a single template name declaration D
229  // or we have a non-empty set of results R containing either one template name
230  // declaration or a set of function templates.
231 
232  TemplateName Template;
233  TemplateNameKind TemplateKind;
234 
235  unsigned ResultCount = R.end() - R.begin();
236  if (!D && ResultCount > 1) {
237  // We assume that we'll preserve the qualifier from a function
238  // template name in other ways.
239  Template = Context.getOverloadedTemplateName(R.begin(), R.end());
240  TemplateKind = TNK_Function_template;
241 
242  // We'll do this lookup again later.
243  R.suppressDiagnostics();
244  } else {
245  if (!D) {
246  D = getAsTemplateNameDecl(*R.begin());
247  assert(D && "unambiguous result is not a template name");
248  }
249 
250  if (isa<UnresolvedUsingValueDecl>(D)) {
251  // We don't yet know whether this is a template-name or not.
252  MemberOfUnknownSpecialization = true;
253  return TNK_Non_template;
254  }
255 
256  TemplateDecl *TD = cast<TemplateDecl>(D);
257 
258  if (SS.isSet() && !SS.isInvalid()) {
259  NestedNameSpecifier *Qualifier = SS.getScopeRep();
260  Template = Context.getQualifiedTemplateName(Qualifier,
261  hasTemplateKeyword, TD);
262  } else {
263  Template = TemplateName(TD);
264  }
265 
266  if (isa<FunctionTemplateDecl>(TD)) {
267  TemplateKind = TNK_Function_template;
268 
269  // We'll do this lookup again later.
270  R.suppressDiagnostics();
271  } else {
272  assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
273  isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
274  isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
275  TemplateKind =
276  isa<VarTemplateDecl>(TD) ? TNK_Var_template :
277  isa<ConceptDecl>(TD) ? TNK_Concept_template :
279  }
280  }
281 
282  TemplateResult = TemplateTy::make(Template);
283  return TemplateKind;
284 }
285 
287  SourceLocation NameLoc,
288  ParsedTemplateTy *Template) {
289  CXXScopeSpec SS;
290  bool MemberOfUnknownSpecialization = false;
291 
292  // We could use redeclaration lookup here, but we don't need to: the
293  // syntactic form of a deduction guide is enough to identify it even
294  // if we can't look up the template name at all.
295  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
296  if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
297  /*EnteringContext*/ false,
298  MemberOfUnknownSpecialization))
299  return false;
300 
301  if (R.empty()) return false;
302  if (R.isAmbiguous()) {
303  // FIXME: Diagnose an ambiguity if we find at least one template.
305  return false;
306  }
307 
308  // We only treat template-names that name type templates as valid deduction
309  // guide names.
311  if (!TD || !getAsTypeTemplateDecl(TD))
312  return false;
313 
314  if (Template)
315  *Template = TemplateTy::make(TemplateName(TD));
316  return true;
317 }
318 
320  SourceLocation IILoc,
321  Scope *S,
322  const CXXScopeSpec *SS,
323  TemplateTy &SuggestedTemplate,
324  TemplateNameKind &SuggestedKind) {
325  // We can't recover unless there's a dependent scope specifier preceding the
326  // template name.
327  // FIXME: Typo correction?
328  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
329  computeDeclContext(*SS))
330  return false;
331 
332  // The code is missing a 'template' keyword prior to the dependent template
333  // name.
335  Diag(IILoc, diag::err_template_kw_missing)
336  << Qualifier << II.getName()
337  << FixItHint::CreateInsertion(IILoc, "template ");
338  SuggestedTemplate
339  = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
340  SuggestedKind = TNK_Dependent_template_name;
341  return true;
342 }
343 
345  Scope *S, CXXScopeSpec &SS,
346  QualType ObjectType,
347  bool EnteringContext,
348  bool &MemberOfUnknownSpecialization,
349  SourceLocation TemplateKWLoc,
350  AssumedTemplateKind *ATK) {
351  if (ATK)
353 
354  Found.setTemplateNameLookup(true);
355 
356  // Determine where to perform name lookup
357  MemberOfUnknownSpecialization = false;
358  DeclContext *LookupCtx = nullptr;
359  bool IsDependent = false;
360  if (!ObjectType.isNull()) {
361  // This nested-name-specifier occurs in a member access expression, e.g.,
362  // x->B::f, and we are looking into the type of the object.
363  assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
364  LookupCtx = computeDeclContext(ObjectType);
365  IsDependent = !LookupCtx && ObjectType->isDependentType();
366  assert((IsDependent || !ObjectType->isIncompleteType() ||
367  ObjectType->castAs<TagType>()->isBeingDefined()) &&
368  "Caller should have completed object type");
369 
370  // Template names cannot appear inside an Objective-C class or object type
371  // or a vector type.
372  //
373  // FIXME: This is wrong. For example:
374  //
375  // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
376  // Vec<int> vi;
377  // vi.Vec<int>::~Vec<int>();
378  //
379  // ... should be accepted but we will not treat 'Vec' as a template name
380  // here. The right thing to do would be to check if the name is a valid
381  // vector component name, and look up a template name if not. And similarly
382  // for lookups into Objective-C class and object types, where the same
383  // problem can arise.
384  if (ObjectType->isObjCObjectOrInterfaceType() ||
385  ObjectType->isVectorType()) {
386  Found.clear();
387  return false;
388  }
389  } else if (SS.isSet()) {
390  // This nested-name-specifier occurs after another nested-name-specifier,
391  // so long into the context associated with the prior nested-name-specifier.
392  LookupCtx = computeDeclContext(SS, EnteringContext);
393  IsDependent = !LookupCtx;
394 
395  // The declaration context must be complete.
396  if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
397  return true;
398  }
399 
400  bool ObjectTypeSearchedInScope = false;
401  bool AllowFunctionTemplatesInLookup = true;
402  if (LookupCtx) {
403  // Perform "qualified" name lookup into the declaration context we
404  // computed, which is either the type of the base of a member access
405  // expression or the declaration context associated with a prior
406  // nested-name-specifier.
407  LookupQualifiedName(Found, LookupCtx);
408 
409  // FIXME: The C++ standard does not clearly specify what happens in the
410  // case where the object type is dependent, and implementations vary. In
411  // Clang, we treat a name after a . or -> as a template-name if lookup
412  // finds a non-dependent member or member of the current instantiation that
413  // is a type template, or finds no such members and lookup in the context
414  // of the postfix-expression finds a type template. In the latter case, the
415  // name is nonetheless dependent, and we may resolve it to a member of an
416  // unknown specialization when we come to instantiate the template.
417  IsDependent |= Found.wasNotFoundInCurrentInstantiation();
418  }
419 
420  if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
421  // C++ [basic.lookup.classref]p1:
422  // In a class member access expression (5.2.5), if the . or -> token is
423  // immediately followed by an identifier followed by a <, the
424  // identifier must be looked up to determine whether the < is the
425  // beginning of a template argument list (14.2) or a less-than operator.
426  // The identifier is first looked up in the class of the object
427  // expression. If the identifier is not found, it is then looked up in
428  // the context of the entire postfix-expression and shall name a class
429  // template.
430  if (S)
431  LookupName(Found, S);
432 
433  if (!ObjectType.isNull()) {
434  // FIXME: We should filter out all non-type templates here, particularly
435  // variable templates and concepts. But the exclusion of alias templates
436  // and template template parameters is a wording defect.
437  AllowFunctionTemplatesInLookup = false;
438  ObjectTypeSearchedInScope = true;
439  }
440 
441  IsDependent |= Found.wasNotFoundInCurrentInstantiation();
442  }
443 
444  if (Found.isAmbiguous())
445  return false;
446 
447  if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
448  // C++2a [temp.names]p2:
449  // A name is also considered to refer to a template if it is an
450  // unqualified-id followed by a < and name lookup finds either one or more
451  // functions or finds nothing.
452  //
453  // To keep our behavior consistent, we apply the "finds nothing" part in
454  // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
455  // successfully form a call to an undeclared template-id.
456  bool AllFunctions =
457  getLangOpts().CPlusPlus2a &&
458  std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
459  return isa<FunctionDecl>(ND->getUnderlyingDecl());
460  });
461  if (AllFunctions || (Found.empty() && !IsDependent)) {
462  // If lookup found any functions, or if this is a name that can only be
463  // used for a function, then strongly assume this is a function
464  // template-id.
465  *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
466  ? AssumedTemplateKind::FoundNothing
467  : AssumedTemplateKind::FoundFunctions;
468  Found.clear();
469  return false;
470  }
471  }
472 
473  if (Found.empty() && !IsDependent) {
474  // If we did not find any names, attempt to correct any typos.
475  DeclarationName Name = Found.getLookupName();
476  Found.clear();
477  // Simple filter callback that, for keywords, only accepts the C++ *_cast
478  DefaultFilterCCC FilterCCC{};
479  FilterCCC.WantTypeSpecifiers = false;
480  FilterCCC.WantExpressionKeywords = false;
481  FilterCCC.WantRemainingKeywords = false;
482  FilterCCC.WantCXXNamedCasts = true;
483  if (TypoCorrection Corrected =
484  CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
485  &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
486  if (auto *ND = Corrected.getFoundDecl())
487  Found.addDecl(ND);
488  FilterAcceptableTemplateNames(Found);
489  if (Found.isAmbiguous()) {
490  Found.clear();
491  } else if (!Found.empty()) {
492  Found.setLookupName(Corrected.getCorrection());
493  if (LookupCtx) {
494  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
495  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
496  Name.getAsString() == CorrectedStr;
497  diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
498  << Name << LookupCtx << DroppedSpecifier
499  << SS.getRange());
500  } else {
501  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
502  }
503  }
504  }
505  }
506 
507  NamedDecl *ExampleLookupResult =
508  Found.empty() ? nullptr : Found.getRepresentativeDecl();
509  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
510  if (Found.empty()) {
511  if (IsDependent) {
512  MemberOfUnknownSpecialization = true;
513  return false;
514  }
515 
516  // If a 'template' keyword was used, a lookup that finds only non-template
517  // names is an error.
518  if (ExampleLookupResult && TemplateKWLoc.isValid()) {
519  Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
520  << Found.getLookupName() << SS.getRange();
521  Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
522  diag::note_template_kw_refers_to_non_template)
523  << Found.getLookupName();
524  return true;
525  }
526 
527  return false;
528  }
529 
530  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
531  !getLangOpts().CPlusPlus11) {
532  // C++03 [basic.lookup.classref]p1:
533  // [...] If the lookup in the class of the object expression finds a
534  // template, the name is also looked up in the context of the entire
535  // postfix-expression and [...]
536  //
537  // Note: C++11 does not perform this second lookup.
538  LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
539  LookupOrdinaryName);
540  FoundOuter.setTemplateNameLookup(true);
541  LookupName(FoundOuter, S);
542  // FIXME: We silently accept an ambiguous lookup here, in violation of
543  // [basic.lookup]/1.
544  FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
545 
546  NamedDecl *OuterTemplate;
547  if (FoundOuter.empty()) {
548  // - if the name is not found, the name found in the class of the
549  // object expression is used, otherwise
550  } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
551  !(OuterTemplate =
552  getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
553  // - if the name is found in the context of the entire
554  // postfix-expression and does not name a class template, the name
555  // found in the class of the object expression is used, otherwise
556  FoundOuter.clear();
557  } else if (!Found.isSuppressingDiagnostics()) {
558  // - if the name found is a class template, it must refer to the same
559  // entity as the one found in the class of the object expression,
560  // otherwise the program is ill-formed.
561  if (!Found.isSingleResult() ||
562  getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
563  OuterTemplate->getCanonicalDecl()) {
564  Diag(Found.getNameLoc(),
565  diag::ext_nested_name_member_ref_lookup_ambiguous)
566  << Found.getLookupName()
567  << ObjectType;
569  diag::note_ambig_member_ref_object_type)
570  << ObjectType;
571  Diag(FoundOuter.getFoundDecl()->getLocation(),
572  diag::note_ambig_member_ref_scope);
573 
574  // Recover by taking the template that we found in the object
575  // expression's type.
576  }
577  }
578  }
579 
580  return false;
581 }
582 
584  SourceLocation Less,
585  SourceLocation Greater) {
586  if (TemplateName.isInvalid())
587  return;
588 
589  DeclarationNameInfo NameInfo;
590  CXXScopeSpec SS;
591  LookupNameKind LookupKind;
592 
593  DeclContext *LookupCtx = nullptr;
594  NamedDecl *Found = nullptr;
595  bool MissingTemplateKeyword = false;
596 
597  // Figure out what name we looked up.
598  if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
599  NameInfo = DRE->getNameInfo();
600  SS.Adopt(DRE->getQualifierLoc());
601  LookupKind = LookupOrdinaryName;
602  Found = DRE->getFoundDecl();
603  } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
604  NameInfo = ME->getMemberNameInfo();
605  SS.Adopt(ME->getQualifierLoc());
606  LookupKind = LookupMemberName;
607  LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
608  Found = ME->getMemberDecl();
609  } else if (auto *DSDRE =
610  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
611  NameInfo = DSDRE->getNameInfo();
612  SS.Adopt(DSDRE->getQualifierLoc());
613  MissingTemplateKeyword = true;
614  } else if (auto *DSME =
615  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
616  NameInfo = DSME->getMemberNameInfo();
617  SS.Adopt(DSME->getQualifierLoc());
618  MissingTemplateKeyword = true;
619  } else {
620  llvm_unreachable("unexpected kind of potential template name");
621  }
622 
623  // If this is a dependent-scope lookup, diagnose that the 'template' keyword
624  // was missing.
625  if (MissingTemplateKeyword) {
626  Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
627  << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
628  return;
629  }
630 
631  // Try to correct the name by looking for templates and C++ named casts.
632  struct TemplateCandidateFilter : CorrectionCandidateCallback {
633  Sema &S;
634  TemplateCandidateFilter(Sema &S) : S(S) {
635  WantTypeSpecifiers = false;
636  WantExpressionKeywords = false;
637  WantRemainingKeywords = false;
638  WantCXXNamedCasts = true;
639  };
640  bool ValidateCandidate(const TypoCorrection &Candidate) override {
641  if (auto *ND = Candidate.getCorrectionDecl())
642  return S.getAsTemplateNameDecl(ND);
643  return Candidate.isKeyword();
644  }
645 
646  std::unique_ptr<CorrectionCandidateCallback> clone() override {
647  return std::make_unique<TemplateCandidateFilter>(*this);
648  }
649  };
650 
651  DeclarationName Name = NameInfo.getName();
652  TemplateCandidateFilter CCC(*this);
653  if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
654  CTK_ErrorRecovery, LookupCtx)) {
655  auto *ND = Corrected.getFoundDecl();
656  if (ND)
657  ND = getAsTemplateNameDecl(ND);
658  if (ND || Corrected.isKeyword()) {
659  if (LookupCtx) {
660  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
661  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
662  Name.getAsString() == CorrectedStr;
663  diagnoseTypo(Corrected,
664  PDiag(diag::err_non_template_in_member_template_id_suggest)
665  << Name << LookupCtx << DroppedSpecifier
666  << SS.getRange(), false);
667  } else {
668  diagnoseTypo(Corrected,
669  PDiag(diag::err_non_template_in_template_id_suggest)
670  << Name, false);
671  }
672  if (Found)
673  Diag(Found->getLocation(),
674  diag::note_non_template_in_template_id_found);
675  return;
676  }
677  }
678 
679  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
680  << Name << SourceRange(Less, Greater);
681  if (Found)
682  Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
683 }
684 
685 /// ActOnDependentIdExpression - Handle a dependent id-expression that
686 /// was just parsed. This is only possible with an explicit scope
687 /// specifier naming a dependent type.
690  SourceLocation TemplateKWLoc,
691  const DeclarationNameInfo &NameInfo,
692  bool isAddressOfOperand,
693  const TemplateArgumentListInfo *TemplateArgs) {
694  DeclContext *DC = getFunctionLevelDeclContext();
695 
696  // C++11 [expr.prim.general]p12:
697  // An id-expression that denotes a non-static data member or non-static
698  // member function of a class can only be used:
699  // (...)
700  // - if that id-expression denotes a non-static data member and it
701  // appears in an unevaluated operand.
702  //
703  // If this might be the case, form a DependentScopeDeclRefExpr instead of a
704  // CXXDependentScopeMemberExpr. The former can instantiate to either
705  // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
706  // always a MemberExpr.
707  bool MightBeCxx11UnevalField =
708  getLangOpts().CPlusPlus11 && isUnevaluatedContext();
709 
710  // Check if the nested name specifier is an enum type.
711  bool IsEnum = false;
712  if (NestedNameSpecifier *NNS = SS.getScopeRep())
713  IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
714 
715  if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
716  isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
717  QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
718 
719  // Since the 'this' expression is synthesized, we don't need to
720  // perform the double-lookup check.
721  NamedDecl *FirstQualifierInScope = nullptr;
722 
724  Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
725  /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
726  FirstQualifierInScope, NameInfo, TemplateArgs);
727  }
728 
729  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
730 }
731 
734  SourceLocation TemplateKWLoc,
735  const DeclarationNameInfo &NameInfo,
736  const TemplateArgumentListInfo *TemplateArgs) {
738  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
739  TemplateArgs);
740 }
741 
742 
743 /// Determine whether we would be unable to instantiate this template (because
744 /// it either has no definition, or is in the process of being instantiated).
746  NamedDecl *Instantiation,
747  bool InstantiatedFromMember,
748  const NamedDecl *Pattern,
749  const NamedDecl *PatternDef,
751  bool Complain /*= true*/) {
752  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
753  isa<VarDecl>(Instantiation));
754 
755  bool IsEntityBeingDefined = false;
756  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
757  IsEntityBeingDefined = TD->isBeingDefined();
758 
759  if (PatternDef && !IsEntityBeingDefined) {
760  NamedDecl *SuggestedDef = nullptr;
761  if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
762  /*OnlyNeedComplete*/false)) {
763  // If we're allowed to diagnose this and recover, do so.
764  bool Recover = Complain && !isSFINAEContext();
765  if (Complain)
766  diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
768  return !Recover;
769  }
770  return false;
771  }
772 
773  if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
774  return true;
775 
777  QualType InstantiationTy;
778  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
779  InstantiationTy = Context.getTypeDeclType(TD);
780  if (PatternDef) {
781  Diag(PointOfInstantiation,
782  diag::err_template_instantiate_within_definition)
783  << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
784  << InstantiationTy;
785  // Not much point in noting the template declaration here, since
786  // we're lexically inside it.
787  Instantiation->setInvalidDecl();
788  } else if (InstantiatedFromMember) {
789  if (isa<FunctionDecl>(Instantiation)) {
790  Diag(PointOfInstantiation,
791  diag::err_explicit_instantiation_undefined_member)
792  << /*member function*/ 1 << Instantiation->getDeclName()
793  << Instantiation->getDeclContext();
794  Note = diag::note_explicit_instantiation_here;
795  } else {
796  assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
797  Diag(PointOfInstantiation,
798  diag::err_implicit_instantiate_member_undefined)
799  << InstantiationTy;
800  Note = diag::note_member_declared_at;
801  }
802  } else {
803  if (isa<FunctionDecl>(Instantiation)) {
804  Diag(PointOfInstantiation,
805  diag::err_explicit_instantiation_undefined_func_template)
806  << Pattern;
807  Note = diag::note_explicit_instantiation_here;
808  } else if (isa<TagDecl>(Instantiation)) {
809  Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
810  << (TSK != TSK_ImplicitInstantiation)
811  << InstantiationTy;
812  Note = diag::note_template_decl_here;
813  } else {
814  assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
815  if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
816  Diag(PointOfInstantiation,
817  diag::err_explicit_instantiation_undefined_var_template)
818  << Instantiation;
819  Instantiation->setInvalidDecl();
820  } else
821  Diag(PointOfInstantiation,
822  diag::err_explicit_instantiation_undefined_member)
823  << /*static data member*/ 2 << Instantiation->getDeclName()
824  << Instantiation->getDeclContext();
825  Note = diag::note_explicit_instantiation_here;
826  }
827  }
828  if (Note) // Diagnostics were emitted.
829  Diag(Pattern->getLocation(), Note.getValue());
830 
831  // In general, Instantiation isn't marked invalid to get more than one
832  // error for multiple undefined instantiations. But the code that does
833  // explicit declaration -> explicit definition conversion can't handle
834  // invalid declarations, so mark as invalid in that case.
836  Instantiation->setInvalidDecl();
837  return true;
838 }
839 
840 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
841 /// that the template parameter 'PrevDecl' is being shadowed by a new
842 /// declaration at location Loc. Returns true to indicate that this is
843 /// an error, and false otherwise.
845  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
846 
847  // Microsoft Visual C++ permits template parameters to be shadowed.
848  if (getLangOpts().MicrosoftExt)
849  return;
850 
851  // C++ [temp.local]p4:
852  // A template-parameter shall not be redeclared within its
853  // scope (including nested scopes).
854  Diag(Loc, diag::err_template_param_shadow)
855  << cast<NamedDecl>(PrevDecl)->getDeclName();
856  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
857 }
858 
859 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
860 /// the parameter D to reference the templated declaration and return a pointer
861 /// to the template declaration. Otherwise, do nothing to D and return null.
863  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
864  D = Temp->getTemplatedDecl();
865  return Temp;
866  }
867  return nullptr;
868 }
869 
871  SourceLocation EllipsisLoc) const {
872  assert(Kind == Template &&
873  "Only template template arguments can be pack expansions here");
874  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
875  "Template template argument pack expansion without packs");
876  ParsedTemplateArgument Result(*this);
877  Result.EllipsisLoc = EllipsisLoc;
878  return Result;
879 }
880 
882  const ParsedTemplateArgument &Arg) {
883 
884  switch (Arg.getKind()) {
886  TypeSourceInfo *DI;
887  QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
888  if (!DI)
889  DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
890  return TemplateArgumentLoc(TemplateArgument(T), DI);
891  }
892 
894  Expr *E = static_cast<Expr *>(Arg.getAsExpr());
896  }
897 
899  TemplateName Template = Arg.getAsTemplate().get();
900  TemplateArgument TArg;
901  if (Arg.getEllipsisLoc().isValid())
902  TArg = TemplateArgument(Template, Optional<unsigned int>());
903  else
904  TArg = Template;
905  return TemplateArgumentLoc(TArg,
907  SemaRef.Context),
908  Arg.getLocation(),
909  Arg.getEllipsisLoc());
910  }
911  }
912 
913  llvm_unreachable("Unhandled parsed template argument");
914 }
915 
916 /// Translates template arguments as provided by the parser
917 /// into template arguments used by semantic analysis.
919  TemplateArgumentListInfo &TemplateArgs) {
920  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
921  TemplateArgs.addArgument(translateTemplateArgument(*this,
922  TemplateArgsIn[I]));
923 }
924 
926  SourceLocation Loc,
927  IdentifierInfo *Name) {
928  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
930  if (PrevDecl && PrevDecl->isTemplateParameter())
931  SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
932 }
933 
934 /// Convert a parsed type into a parsed template argument. This is mostly
935 /// trivial, except that we may have parsed a C++17 deduced class template
936 /// specialization type, in which case we should form a template template
937 /// argument instead of a type template argument.
939  TypeSourceInfo *TInfo;
940  QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
941  if (T.isNull())
942  return ParsedTemplateArgument();
943  assert(TInfo && "template argument with no location");
944 
945  // If we might have formed a deduced template specialization type, convert
946  // it to a template template argument.
947  if (getLangOpts().CPlusPlus17) {
948  TypeLoc TL = TInfo->getTypeLoc();
949  SourceLocation EllipsisLoc;
950  if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
951  EllipsisLoc = PET.getEllipsisLoc();
952  TL = PET.getPatternLoc();
953  }
954 
955  CXXScopeSpec SS;
956  if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
957  SS.Adopt(ET.getQualifierLoc());
958  TL = ET.getNamedTypeLoc();
959  }
960 
961  if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
962  TemplateName Name = DTST.getTypePtr()->getTemplateName();
963  if (SS.isSet())
964  Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
965  /*HasTemplateKeyword*/ false,
966  Name.getAsTemplateDecl());
967  ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
968  DTST.getTemplateNameLoc());
969  if (EllipsisLoc.isValid())
970  Result = Result.getTemplatePackExpansion(EllipsisLoc);
971  return Result;
972  }
973  }
974 
975  // This is a normal type template argument. Note, if the type template
976  // argument is an injected-class-name for a template, it has a dual nature
977  // and can be used as either a type or a template. We handle that in
978  // convertTypeTemplateArgumentToTemplate.
980  ParsedType.get().getAsOpaquePtr(),
981  TInfo->getTypeLoc().getBeginLoc());
982 }
983 
984 /// ActOnTypeParameter - Called when a C++ template type parameter
985 /// (e.g., "typename T") has been parsed. Typename specifies whether
986 /// the keyword "typename" was used to declare the type parameter
987 /// (otherwise, "class" was used), and KeyLoc is the location of the
988 /// "class" or "typename" keyword. ParamName is the name of the
989 /// parameter (NULL indicates an unnamed template parameter) and
990 /// ParamNameLoc is the location of the parameter name (if any).
991 /// If the type parameter has a default argument, it will be added
992 /// later via ActOnTypeParameterDefault.
994  SourceLocation EllipsisLoc,
995  SourceLocation KeyLoc,
996  IdentifierInfo *ParamName,
997  SourceLocation ParamNameLoc,
998  unsigned Depth, unsigned Position,
999  SourceLocation EqualLoc,
1000  ParsedType DefaultArg) {
1001  assert(S->isTemplateParamScope() &&
1002  "Template type parameter not in template parameter scope!");
1003 
1004  SourceLocation Loc = ParamNameLoc;
1005  if (!ParamName)
1006  Loc = KeyLoc;
1007 
1008  bool IsParameterPack = EllipsisLoc.isValid();
1009  TemplateTypeParmDecl *Param
1011  KeyLoc, Loc, Depth, Position, ParamName,
1012  Typename, IsParameterPack);
1013  Param->setAccess(AS_public);
1014 
1015  if (ParamName) {
1016  maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1017 
1018  // Add the template parameter into the current scope.
1019  S->AddDecl(Param);
1020  IdResolver.AddDecl(Param);
1021  }
1022 
1023  // C++0x [temp.param]p9:
1024  // A default template-argument may be specified for any kind of
1025  // template-parameter that is not a template parameter pack.
1026  if (DefaultArg && IsParameterPack) {
1027  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1028  DefaultArg = nullptr;
1029  }
1030 
1031  // Handle the default argument, if provided.
1032  if (DefaultArg) {
1033  TypeSourceInfo *DefaultTInfo;
1034  GetTypeFromParser(DefaultArg, &DefaultTInfo);
1035 
1036  assert(DefaultTInfo && "expected source information for type");
1037 
1038  // Check for unexpanded parameter packs.
1039  if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
1040  UPPC_DefaultArgument))
1041  return Param;
1042 
1043  // Check the template argument itself.
1044  if (CheckTemplateArgument(Param, DefaultTInfo)) {
1045  Param->setInvalidDecl();
1046  return Param;
1047  }
1048 
1049  Param->setDefaultArgument(DefaultTInfo);
1050  }
1051 
1052  return Param;
1053 }
1054 
1055 /// Check that the type of a non-type template parameter is
1056 /// well-formed.
1057 ///
1058 /// \returns the (possibly-promoted) parameter type if valid;
1059 /// otherwise, produces a diagnostic and returns a NULL type.
1061  SourceLocation Loc) {
1062  if (TSI->getType()->isUndeducedType()) {
1063  // C++17 [temp.dep.expr]p3:
1064  // An id-expression is type-dependent if it contains
1065  // - an identifier associated by name lookup with a non-type
1066  // template-parameter declared with a type that contains a
1067  // placeholder type (7.1.7.4),
1068  TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1069  }
1070 
1071  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1072 }
1073 
1075  SourceLocation Loc) {
1076  // We don't allow variably-modified types as the type of non-type template
1077  // parameters.
1078  if (T->isVariablyModifiedType()) {
1079  Diag(Loc, diag::err_variably_modified_nontype_template_param)
1080  << T;
1081  return QualType();
1082  }
1083 
1084  // C++ [temp.param]p4:
1085  //
1086  // A non-type template-parameter shall have one of the following
1087  // (optionally cv-qualified) types:
1088  //
1089  // -- integral or enumeration type,
1090  if (T->isIntegralOrEnumerationType() ||
1091  // -- pointer to object or pointer to function,
1092  T->isPointerType() ||
1093  // -- reference to object or reference to function,
1094  T->isReferenceType() ||
1095  // -- pointer to member,
1096  T->isMemberPointerType() ||
1097  // -- std::nullptr_t.
1098  T->isNullPtrType() ||
1099  // If T is a dependent type, we can't do the check now, so we
1100  // assume that it is well-formed.
1101  T->isDependentType() ||
1102  // Allow use of auto in template parameter declarations.
1103  T->isUndeducedType()) {
1104  // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1105  // are ignored when determining its type.
1106  return T.getUnqualifiedType();
1107  }
1108 
1109  // C++ [temp.param]p8:
1110  //
1111  // A non-type template-parameter of type "array of T" or
1112  // "function returning T" is adjusted to be of type "pointer to
1113  // T" or "pointer to function returning T", respectively.
1114  else if (T->isArrayType() || T->isFunctionType())
1115  return Context.getDecayedType(T);
1116 
1117  Diag(Loc, diag::err_template_nontype_parm_bad_type)
1118  << T;
1119 
1120  return QualType();
1121 }
1122 
1124  unsigned Depth,
1125  unsigned Position,
1126  SourceLocation EqualLoc,
1127  Expr *Default) {
1128  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1129 
1130  // Check that we have valid decl-specifiers specified.
1131  auto CheckValidDeclSpecifiers = [this, &D] {
1132  // C++ [temp.param]
1133  // p1
1134  // template-parameter:
1135  // ...
1136  // parameter-declaration
1137  // p2
1138  // ... A storage class shall not be specified in a template-parameter
1139  // declaration.
1140  // [dcl.typedef]p1:
1141  // The typedef specifier [...] shall not be used in the decl-specifier-seq
1142  // of a parameter-declaration
1143  const DeclSpec &DS = D.getDeclSpec();
1144  auto EmitDiag = [this](SourceLocation Loc) {
1145  Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1146  << FixItHint::CreateRemoval(Loc);
1147  };
1149  EmitDiag(DS.getStorageClassSpecLoc());
1150 
1152  EmitDiag(DS.getThreadStorageClassSpecLoc());
1153 
1154  // [dcl.inline]p1:
1155  // The inline specifier can be applied only to the declaration or
1156  // definition of a variable or function.
1157 
1158  if (DS.isInlineSpecified())
1159  EmitDiag(DS.getInlineSpecLoc());
1160 
1161  // [dcl.constexpr]p1:
1162  // The constexpr specifier shall be applied only to the definition of a
1163  // variable or variable template or the declaration of a function or
1164  // function template.
1165 
1166  if (DS.hasConstexprSpecifier())
1167  EmitDiag(DS.getConstexprSpecLoc());
1168 
1169  // [dcl.fct.spec]p1:
1170  // Function-specifiers can be used only in function declarations.
1171 
1172  if (DS.isVirtualSpecified())
1173  EmitDiag(DS.getVirtualSpecLoc());
1174 
1175  if (DS.hasExplicitSpecifier())
1176  EmitDiag(DS.getExplicitSpecLoc());
1177 
1178  if (DS.isNoreturnSpecified())
1179  EmitDiag(DS.getNoreturnSpecLoc());
1180  };
1181 
1182  CheckValidDeclSpecifiers();
1183 
1184  if (TInfo->getType()->isUndeducedType()) {
1185  Diag(D.getIdentifierLoc(),
1186  diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1187  << QualType(TInfo->getType()->getContainedAutoType(), 0);
1188  }
1189 
1190  assert(S->isTemplateParamScope() &&
1191  "Non-type template parameter not in template parameter scope!");
1192  bool Invalid = false;
1193 
1194  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1195  if (T.isNull()) {
1196  T = Context.IntTy; // Recover with an 'int' type.
1197  Invalid = true;
1198  }
1199 
1200  CheckFunctionOrTemplateParamDeclarator(S, D);
1201 
1202  IdentifierInfo *ParamName = D.getIdentifier();
1203  bool IsParameterPack = D.hasEllipsis();
1205  Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1206  D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1207  TInfo);
1208  Param->setAccess(AS_public);
1209 
1210  if (Invalid)
1211  Param->setInvalidDecl();
1212 
1213  if (ParamName) {
1215  ParamName);
1216 
1217  // Add the template parameter into the current scope.
1218  S->AddDecl(Param);
1219  IdResolver.AddDecl(Param);
1220  }
1221 
1222  // C++0x [temp.param]p9:
1223  // A default template-argument may be specified for any kind of
1224  // template-parameter that is not a template parameter pack.
1225  if (Default && IsParameterPack) {
1226  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1227  Default = nullptr;
1228  }
1229 
1230  // Check the well-formedness of the default template argument, if provided.
1231  if (Default) {
1232  // Check for unexpanded parameter packs.
1233  if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1234  return Param;
1235 
1236  TemplateArgument Converted;
1237  ExprResult DefaultRes =
1238  CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1239  if (DefaultRes.isInvalid()) {
1240  Param->setInvalidDecl();
1241  return Param;
1242  }
1243  Default = DefaultRes.get();
1244 
1245  Param->setDefaultArgument(Default);
1246  }
1247 
1248  return Param;
1249 }
1250 
1251 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1252 /// parameter (e.g. T in template <template <typename> class T> class array)
1253 /// has been parsed. S is the current scope.
1255  SourceLocation TmpLoc,
1256  TemplateParameterList *Params,
1257  SourceLocation EllipsisLoc,
1258  IdentifierInfo *Name,
1259  SourceLocation NameLoc,
1260  unsigned Depth,
1261  unsigned Position,
1262  SourceLocation EqualLoc,
1263  ParsedTemplateArgument Default) {
1264  assert(S->isTemplateParamScope() &&
1265  "Template template parameter not in template parameter scope!");
1266 
1267  // Construct the parameter object.
1268  bool IsParameterPack = EllipsisLoc.isValid();
1269  TemplateTemplateParmDecl *Param =
1271  NameLoc.isInvalid()? TmpLoc : NameLoc,
1272  Depth, Position, IsParameterPack,
1273  Name, Params);
1274  Param->setAccess(AS_public);
1275 
1276  // If the template template parameter has a name, then link the identifier
1277  // into the scope and lookup mechanisms.
1278  if (Name) {
1279  maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1280 
1281  S->AddDecl(Param);
1282  IdResolver.AddDecl(Param);
1283  }
1284 
1285  if (Params->size() == 0) {
1286  Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1287  << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1288  Param->setInvalidDecl();
1289  }
1290 
1291  // C++0x [temp.param]p9:
1292  // A default template-argument may be specified for any kind of
1293  // template-parameter that is not a template parameter pack.
1294  if (IsParameterPack && !Default.isInvalid()) {
1295  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1296  Default = ParsedTemplateArgument();
1297  }
1298 
1299  if (!Default.isInvalid()) {
1300  // Check only that we have a template template argument. We don't want to
1301  // try to check well-formedness now, because our template template parameter
1302  // might have dependent types in its template parameters, which we wouldn't
1303  // be able to match now.
1304  //
1305  // If none of the template template parameter's template arguments mention
1306  // other template parameters, we could actually perform more checking here.
1307  // However, it isn't worth doing.
1308  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1309  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1310  Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1311  << DefaultArg.getSourceRange();
1312  return Param;
1313  }
1314 
1315  // Check for unexpanded parameter packs.
1316  if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1317  DefaultArg.getArgument().getAsTemplate(),
1318  UPPC_DefaultArgument))
1319  return Param;
1320 
1321  Param->setDefaultArgument(Context, DefaultArg);
1322  }
1323 
1324  return Param;
1325 }
1326 
1327 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1328 /// constrained by RequiresClause, that contains the template parameters in
1329 /// Params.
1332  SourceLocation ExportLoc,
1333  SourceLocation TemplateLoc,
1334  SourceLocation LAngleLoc,
1335  ArrayRef<NamedDecl *> Params,
1336  SourceLocation RAngleLoc,
1337  Expr *RequiresClause) {
1338  if (ExportLoc.isValid())
1339  Diag(ExportLoc, diag::warn_template_export_unsupported);
1340 
1342  Context, TemplateLoc, LAngleLoc,
1343  llvm::makeArrayRef(Params.data(), Params.size()),
1344  RAngleLoc, RequiresClause);
1345 }
1346 
1348  const CXXScopeSpec &SS) {
1349  if (SS.isSet())
1351 }
1352 
1354  Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1355  CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1356  const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1357  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1358  SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1359  TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1360  assert(TemplateParams && TemplateParams->size() > 0 &&
1361  "No template parameters");
1362  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1363  bool Invalid = false;
1364 
1365  // Check that we can declare a template here.
1366  if (CheckTemplateDeclScope(S, TemplateParams))
1367  return true;
1368 
1370  assert(Kind != TTK_Enum && "can't build template of enumerated type");
1371 
1372  // There is no such thing as an unnamed class template.
1373  if (!Name) {
1374  Diag(KWLoc, diag::err_template_unnamed_class);
1375  return true;
1376  }
1377 
1378  // Find any previous declaration with this name. For a friend with no
1379  // scope explicitly specified, we only look for tag declarations (per
1380  // C++11 [basic.lookup.elab]p2).
1381  DeclContext *SemanticContext;
1382  LookupResult Previous(*this, Name, NameLoc,
1383  (SS.isEmpty() && TUK == TUK_Friend)
1384  ? LookupTagName : LookupOrdinaryName,
1385  forRedeclarationInCurContext());
1386  if (SS.isNotEmpty() && !SS.isInvalid()) {
1387  SemanticContext = computeDeclContext(SS, true);
1388  if (!SemanticContext) {
1389  // FIXME: Horrible, horrible hack! We can't currently represent this
1390  // in the AST, and historically we have just ignored such friend
1391  // class templates, so don't complain here.
1392  Diag(NameLoc, TUK == TUK_Friend
1393  ? diag::warn_template_qualified_friend_ignored
1394  : diag::err_template_qualified_declarator_no_match)
1395  << SS.getScopeRep() << SS.getRange();
1396  return TUK != TUK_Friend;
1397  }
1398 
1399  if (RequireCompleteDeclContext(SS, SemanticContext))
1400  return true;
1401 
1402  // If we're adding a template to a dependent context, we may need to
1403  // rebuilding some of the types used within the template parameter list,
1404  // now that we know what the current instantiation is.
1405  if (SemanticContext->isDependentContext()) {
1406  ContextRAII SavedContext(*this, SemanticContext);
1407  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1408  Invalid = true;
1409  } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1410  diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1411 
1412  LookupQualifiedName(Previous, SemanticContext);
1413  } else {
1414  SemanticContext = CurContext;
1415 
1416  // C++14 [class.mem]p14:
1417  // If T is the name of a class, then each of the following shall have a
1418  // name different from T:
1419  // -- every member template of class T
1420  if (TUK != TUK_Friend &&
1421  DiagnoseClassNameShadow(SemanticContext,
1422  DeclarationNameInfo(Name, NameLoc)))
1423  return true;
1424 
1425  LookupName(Previous, S);
1426  }
1427 
1428  if (Previous.isAmbiguous())
1429  return true;
1430 
1431  NamedDecl *PrevDecl = nullptr;
1432  if (Previous.begin() != Previous.end())
1433  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1434 
1435  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1436  // Maybe we will complain about the shadowed template parameter.
1437  DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1438  // Just pretend that we didn't see the previous declaration.
1439  PrevDecl = nullptr;
1440  }
1441 
1442  // If there is a previous declaration with the same name, check
1443  // whether this is a valid redeclaration.
1444  ClassTemplateDecl *PrevClassTemplate =
1445  dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1446 
1447  // We may have found the injected-class-name of a class template,
1448  // class template partial specialization, or class template specialization.
1449  // In these cases, grab the template that is being defined or specialized.
1450  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1451  cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1452  PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1453  PrevClassTemplate
1454  = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1455  if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1456  PrevClassTemplate
1457  = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1458  ->getSpecializedTemplate();
1459  }
1460  }
1461 
1462  if (TUK == TUK_Friend) {
1463  // C++ [namespace.memdef]p3:
1464  // [...] When looking for a prior declaration of a class or a function
1465  // declared as a friend, and when the name of the friend class or
1466  // function is neither a qualified name nor a template-id, scopes outside
1467  // the innermost enclosing namespace scope are not considered.
1468  if (!SS.isSet()) {
1469  DeclContext *OutermostContext = CurContext;
1470  while (!OutermostContext->isFileContext())
1471  OutermostContext = OutermostContext->getLookupParent();
1472 
1473  if (PrevDecl &&
1474  (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1475  OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1476  SemanticContext = PrevDecl->getDeclContext();
1477  } else {
1478  // Declarations in outer scopes don't matter. However, the outermost
1479  // context we computed is the semantic context for our new
1480  // declaration.
1481  PrevDecl = PrevClassTemplate = nullptr;
1482  SemanticContext = OutermostContext;
1483 
1484  // Check that the chosen semantic context doesn't already contain a
1485  // declaration of this name as a non-tag type.
1486  Previous.clear(LookupOrdinaryName);
1487  DeclContext *LookupContext = SemanticContext;
1488  while (LookupContext->isTransparentContext())
1489  LookupContext = LookupContext->getLookupParent();
1490  LookupQualifiedName(Previous, LookupContext);
1491 
1492  if (Previous.isAmbiguous())
1493  return true;
1494 
1495  if (Previous.begin() != Previous.end())
1496  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1497  }
1498  }
1499  } else if (PrevDecl &&
1500  !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1501  S, SS.isValid()))
1502  PrevDecl = PrevClassTemplate = nullptr;
1503 
1504  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1505  PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1506  if (SS.isEmpty() &&
1507  !(PrevClassTemplate &&
1508  PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1509  SemanticContext->getRedeclContext()))) {
1510  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1511  Diag(Shadow->getTargetDecl()->getLocation(),
1512  diag::note_using_decl_target);
1513  Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1514  // Recover by ignoring the old declaration.
1515  PrevDecl = PrevClassTemplate = nullptr;
1516  }
1517  }
1518 
1519  // TODO Memory management; associated constraints are not always stored.
1520  Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1521 
1522  if (PrevClassTemplate) {
1523  // Ensure that the template parameter lists are compatible. Skip this check
1524  // for a friend in a dependent context: the template parameter list itself
1525  // could be dependent.
1526  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1527  !TemplateParameterListsAreEqual(TemplateParams,
1528  PrevClassTemplate->getTemplateParameters(),
1529  /*Complain=*/true,
1530  TPL_TemplateMatch))
1531  return true;
1532 
1533  // Check for matching associated constraints on redeclarations.
1534  const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1535  const bool RedeclACMismatch = [&] {
1536  if (!(CurAC || PrevAC))
1537  return false; // Nothing to check; no mismatch.
1538  if (CurAC && PrevAC) {
1539  llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1540  CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1541  PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1542  if (CurACInfo == PrevACInfo)
1543  return false; // All good; no mismatch.
1544  }
1545  return true;
1546  }();
1547 
1548  if (RedeclACMismatch) {
1549  Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
1550  diag::err_template_different_associated_constraints);
1551  Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1552  diag::note_template_prev_declaration)
1553  << /*declaration*/ 0;
1554  return true;
1555  }
1556 
1557  // C++ [temp.class]p4:
1558  // In a redeclaration, partial specialization, explicit
1559  // specialization or explicit instantiation of a class template,
1560  // the class-key shall agree in kind with the original class
1561  // template declaration (7.1.5.3).
1562  RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1563  if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1564  TUK == TUK_Definition, KWLoc, Name)) {
1565  Diag(KWLoc, diag::err_use_with_wrong_tag)
1566  << Name
1567  << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1568  Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1569  Kind = PrevRecordDecl->getTagKind();
1570  }
1571 
1572  // Check for redefinition of this class template.
1573  if (TUK == TUK_Definition) {
1574  if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1575  // If we have a prior definition that is not visible, treat this as
1576  // simply making that previous definition visible.
1577  NamedDecl *Hidden = nullptr;
1578  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1579  SkipBody->ShouldSkip = true;
1580  SkipBody->Previous = Def;
1581  auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1582  assert(Tmpl && "original definition of a class template is not a "
1583  "class template?");
1584  makeMergedDefinitionVisible(Hidden);
1585  makeMergedDefinitionVisible(Tmpl);
1586  } else {
1587  Diag(NameLoc, diag::err_redefinition) << Name;
1588  Diag(Def->getLocation(), diag::note_previous_definition);
1589  // FIXME: Would it make sense to try to "forget" the previous
1590  // definition, as part of error recovery?
1591  return true;
1592  }
1593  }
1594  }
1595  } else if (PrevDecl) {
1596  // C++ [temp]p5:
1597  // A class template shall not have the same name as any other
1598  // template, class, function, object, enumeration, enumerator,
1599  // namespace, or type in the same scope (3.3), except as specified
1600  // in (14.5.4).
1601  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1602  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1603  return true;
1604  }
1605 
1606  // Check the template parameter list of this declaration, possibly
1607  // merging in the template parameter list from the previous class
1608  // template declaration. Skip this check for a friend in a dependent
1609  // context, because the template parameter list might be dependent.
1610  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1611  CheckTemplateParameterList(
1612  TemplateParams,
1613  PrevClassTemplate
1614  ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1615  : nullptr,
1616  (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1617  SemanticContext->isDependentContext())
1618  ? TPC_ClassTemplateMember
1619  : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1620  SkipBody))
1621  Invalid = true;
1622 
1623  if (SS.isSet()) {
1624  // If the name of the template was qualified, we must be defining the
1625  // template out-of-line.
1626  if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1627  Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1628  : diag::err_member_decl_does_not_match)
1629  << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1630  Invalid = true;
1631  }
1632  }
1633 
1634  // If this is a templated friend in a dependent context we should not put it
1635  // on the redecl chain. In some cases, the templated friend can be the most
1636  // recent declaration tricking the template instantiator to make substitutions
1637  // there.
1638  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1639  bool ShouldAddRedecl
1640  = !(TUK == TUK_Friend && CurContext->isDependentContext());
1641 
1642  CXXRecordDecl *NewClass =
1643  CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1644  PrevClassTemplate && ShouldAddRedecl ?
1645  PrevClassTemplate->getTemplatedDecl() : nullptr,
1646  /*DelayTypeCreation=*/true);
1647  SetNestedNameSpecifier(*this, NewClass, SS);
1648  if (NumOuterTemplateParamLists > 0)
1650  Context, llvm::makeArrayRef(OuterTemplateParamLists,
1651  NumOuterTemplateParamLists));
1652 
1653  // Add alignment attributes if necessary; these attributes are checked when
1654  // the ASTContext lays out the structure.
1655  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1656  AddAlignmentAttributesForRecord(NewClass);
1657  AddMsStructLayoutForRecord(NewClass);
1658  }
1659 
1660  // Attach the associated constraints when the declaration will not be part of
1661  // a decl chain.
1662  Expr *const ACtoAttach =
1663  PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1664 
1665  ClassTemplateDecl *NewTemplate
1666  = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1667  DeclarationName(Name), TemplateParams,
1668  NewClass, ACtoAttach);
1669 
1670  if (ShouldAddRedecl)
1671  NewTemplate->setPreviousDecl(PrevClassTemplate);
1672 
1673  NewClass->setDescribedClassTemplate(NewTemplate);
1674 
1675  if (ModulePrivateLoc.isValid())
1676  NewTemplate->setModulePrivate();
1677 
1678  // Build the type for the class template declaration now.
1679  QualType T = NewTemplate->getInjectedClassNameSpecialization();
1680  T = Context.getInjectedClassNameType(NewClass, T);
1681  assert(T->isDependentType() && "Class template type is not dependent?");
1682  (void)T;
1683 
1684  // If we are providing an explicit specialization of a member that is a
1685  // class template, make a note of that.
1686  if (PrevClassTemplate &&
1687  PrevClassTemplate->getInstantiatedFromMemberTemplate())
1688  PrevClassTemplate->setMemberSpecialization();
1689 
1690  // Set the access specifier.
1691  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1692  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1693 
1694  // Set the lexical context of these templates
1695  NewClass->setLexicalDeclContext(CurContext);
1696  NewTemplate->setLexicalDeclContext(CurContext);
1697 
1698  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
1699  NewClass->startDefinition();
1700 
1701  ProcessDeclAttributeList(S, NewClass, Attr);
1702 
1703  if (PrevClassTemplate)
1704  mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1705 
1706  AddPushedVisibilityAttribute(NewClass);
1707  inferGslOwnerPointerAttribute(NewClass);
1708 
1709  if (TUK != TUK_Friend) {
1710  // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1711  Scope *Outer = S;
1712  while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1713  Outer = Outer->getParent();
1714  PushOnScopeChains(NewTemplate, Outer);
1715  } else {
1716  if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1717  NewTemplate->setAccess(PrevClassTemplate->getAccess());
1718  NewClass->setAccess(PrevClassTemplate->getAccess());
1719  }
1720 
1721  NewTemplate->setObjectOfFriendDecl();
1722 
1723  // Friend templates are visible in fairly strange ways.
1724  if (!CurContext->isDependentContext()) {
1725  DeclContext *DC = SemanticContext->getRedeclContext();
1726  DC->makeDeclVisibleInContext(NewTemplate);
1727  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1728  PushOnScopeChains(NewTemplate, EnclosingScope,
1729  /* AddToContext = */ false);
1730  }
1731 
1732  FriendDecl *Friend = FriendDecl::Create(
1733  Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1734  Friend->setAccess(AS_public);
1735  CurContext->addDecl(Friend);
1736  }
1737 
1738  if (PrevClassTemplate)
1739  CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1740 
1741  if (Invalid) {
1742  NewTemplate->setInvalidDecl();
1743  NewClass->setInvalidDecl();
1744  }
1745 
1746  ActOnDocumentableDecl(NewTemplate);
1747 
1748  if (SkipBody && SkipBody->ShouldSkip)
1749  return SkipBody->Previous;
1750 
1751  return NewTemplate;
1752 }
1753 
1754 namespace {
1755 /// Tree transform to "extract" a transformed type from a class template's
1756 /// constructor to a deduction guide.
1757 class ExtractTypeForDeductionGuide
1758  : public TreeTransform<ExtractTypeForDeductionGuide> {
1759 public:
1761  ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1762 
1763  TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1764 
1765  QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1766  return TransformType(
1767  TLB,
1769  }
1770 };
1771 
1772 /// Transform to convert portions of a constructor declaration into the
1773 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1774 struct ConvertConstructorToDeductionGuideTransform {
1775  ConvertConstructorToDeductionGuideTransform(Sema &S,
1776  ClassTemplateDecl *Template)
1777  : SemaRef(S), Template(Template) {}
1778 
1779  Sema &SemaRef;
1780  ClassTemplateDecl *Template;
1781 
1782  DeclContext *DC = Template->getDeclContext();
1783  CXXRecordDecl *Primary = Template->getTemplatedDecl();
1784  DeclarationName DeductionGuideName =
1786 
1787  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1788 
1789  // Index adjustment to apply to convert depth-1 template parameters into
1790  // depth-0 template parameters.
1791  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1792 
1793  /// Transform a constructor declaration into a deduction guide.
1794  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1795  CXXConstructorDecl *CD) {
1797 
1798  LocalInstantiationScope Scope(SemaRef);
1799 
1800  // C++ [over.match.class.deduct]p1:
1801  // -- For each constructor of the class template designated by the
1802  // template-name, a function template with the following properties:
1803 
1804  // -- The template parameters are the template parameters of the class
1805  // template followed by the template parameters (including default
1806  // template arguments) of the constructor, if any.
1807  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1808  if (FTD) {
1809  TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1810  SmallVector<NamedDecl *, 16> AllParams;
1811  AllParams.reserve(TemplateParams->size() + InnerParams->size());
1812  AllParams.insert(AllParams.begin(),
1813  TemplateParams->begin(), TemplateParams->end());
1814  SubstArgs.reserve(InnerParams->size());
1815 
1816  // Later template parameters could refer to earlier ones, so build up
1817  // a list of substituted template arguments as we go.
1818  for (NamedDecl *Param : *InnerParams) {
1820  Args.addOuterTemplateArguments(SubstArgs);
1821  Args.addOuterRetainedLevel();
1822  NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1823  if (!NewParam)
1824  return nullptr;
1825  AllParams.push_back(NewParam);
1826  SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1827  SemaRef.Context.getInjectedTemplateArg(NewParam)));
1828  }
1829  TemplateParams = TemplateParameterList::Create(
1830  SemaRef.Context, InnerParams->getTemplateLoc(),
1831  InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1832  /*FIXME: RequiresClause*/ nullptr);
1833  }
1834 
1835  // If we built a new template-parameter-list, track that we need to
1836  // substitute references to the old parameters into references to the
1837  // new ones.
1839  if (FTD) {
1840  Args.addOuterTemplateArguments(SubstArgs);
1841  Args.addOuterRetainedLevel();
1842  }
1843 
1846  assert(FPTL && "no prototype for constructor declaration");
1847 
1848  // Transform the type of the function, adjusting the return type and
1849  // replacing references to the old parameters with references to the
1850  // new ones.
1851  TypeLocBuilder TLB;
1853  QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1854  if (NewType.isNull())
1855  return nullptr;
1856  TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1857 
1858  return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1859  NewTInfo, CD->getBeginLoc(), CD->getLocation(),
1860  CD->getEndLoc());
1861  }
1862 
1863  /// Build a deduction guide with the specified parameter types.
1864  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1865  SourceLocation Loc = Template->getLocation();
1866 
1867  // Build the requested type.
1869  EPI.HasTrailingReturn = true;
1870  QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1871  DeductionGuideName, EPI);
1872  TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1873 
1874  FunctionProtoTypeLoc FPTL =
1876 
1877  // Build the parameters, needed during deduction / substitution.
1879  for (auto T : ParamTypes) {
1880  ParmVarDecl *NewParam = ParmVarDecl::Create(
1881  SemaRef.Context, DC, Loc, Loc, nullptr, T,
1882  SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1883  NewParam->setScopeInfo(0, Params.size());
1884  FPTL.setParam(Params.size(), NewParam);
1885  Params.push_back(NewParam);
1886  }
1887 
1888  return buildDeductionGuide(Template->getTemplateParameters(),
1889  ExplicitSpecifier(), TSI, Loc, Loc, Loc);
1890  }
1891 
1892 private:
1893  /// Transform a constructor template parameter into a deduction guide template
1894  /// parameter, rebuilding any internal references to earlier parameters and
1895  /// renumbering as we go.
1896  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1898  if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1899  // TemplateTypeParmDecl's index cannot be changed after creation, so
1900  // substitute it directly.
1901  auto *NewTTP = TemplateTypeParmDecl::Create(
1902  SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1903  /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
1904  TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1905  TTP->isParameterPack());
1906  if (TTP->hasDefaultArgument()) {
1907  TypeSourceInfo *InstantiatedDefaultArg =
1908  SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1909  TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1910  if (InstantiatedDefaultArg)
1911  NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1912  }
1913  SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1914  NewTTP);
1915  return NewTTP;
1916  }
1917 
1918  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1919  return transformTemplateParameterImpl(TTP, Args);
1920 
1921  return transformTemplateParameterImpl(
1922  cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1923  }
1924  template<typename TemplateParmDecl>
1925  TemplateParmDecl *
1926  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1928  // Ask the template instantiator to do the heavy lifting for us, then adjust
1929  // the index of the parameter once it's done.
1930  auto *NewParam =
1931  cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1932  assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1933  NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1934  return NewParam;
1935  }
1936 
1937  QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1941  SmallVector<QualType, 4> ParamTypes;
1942  const FunctionProtoType *T = TL.getTypePtr();
1943 
1944  // -- The types of the function parameters are those of the constructor.
1945  for (auto *OldParam : TL.getParams()) {
1946  ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1947  if (!NewParam)
1948  return QualType();
1949  ParamTypes.push_back(NewParam->getType());
1950  Params.push_back(NewParam);
1951  }
1952 
1953  // -- The return type is the class template specialization designated by
1954  // the template-name and template arguments corresponding to the
1955  // template parameters obtained from the class template.
1956  //
1957  // We use the injected-class-name type of the primary template instead.
1958  // This has the convenient property that it is different from any type that
1959  // the user can write in a deduction-guide (because they cannot enter the
1960  // context of the template), so implicit deduction guides can never collide
1961  // with explicit ones.
1962  QualType ReturnType = DeducedType;
1963  TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1964 
1965  // Resolving a wording defect, we also inherit the variadicness of the
1966  // constructor.
1968  EPI.Variadic = T->isVariadic();
1969  EPI.HasTrailingReturn = true;
1970 
1971  QualType Result = SemaRef.BuildFunctionType(
1972  ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
1973  if (Result.isNull())
1974  return QualType();
1975 
1976  FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1978  NewTL.setLParenLoc(TL.getLParenLoc());
1979  NewTL.setRParenLoc(TL.getRParenLoc());
1981  NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1982  for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1983  NewTL.setParam(I, Params[I]);
1984 
1985  return Result;
1986  }
1987 
1988  ParmVarDecl *
1989  transformFunctionTypeParam(ParmVarDecl *OldParam,
1991  TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1992  TypeSourceInfo *NewDI;
1993  if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1994  // Expand out the one and only element in each inner pack.
1995  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1996  NewDI =
1997  SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1998  OldParam->getLocation(), OldParam->getDeclName());
1999  if (!NewDI) return nullptr;
2000  NewDI =
2001  SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2002  PackTL.getTypePtr()->getNumExpansions());
2003  } else
2004  NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2005  OldParam->getDeclName());
2006  if (!NewDI)
2007  return nullptr;
2008 
2009  // Extract the type. This (for instance) replaces references to typedef
2010  // members of the current instantiations with the definitions of those
2011  // typedefs, avoiding triggering instantiation of the deduced type during
2012  // deduction.
2013  NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
2014 
2015  // Resolving a wording defect, we also inherit default arguments from the
2016  // constructor.
2017  ExprResult NewDefArg;
2018  if (OldParam->hasDefaultArg()) {
2019  NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
2020  if (NewDefArg.isInvalid())
2021  return nullptr;
2022  }
2023 
2024  ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2025  OldParam->getInnerLocStart(),
2026  OldParam->getLocation(),
2027  OldParam->getIdentifier(),
2028  NewDI->getType(),
2029  NewDI,
2030  OldParam->getStorageClass(),
2031  NewDefArg.get());
2032  NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2033  OldParam->getFunctionScopeIndex());
2034  SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2035  return NewParam;
2036  }
2037 
2038  NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
2039  ExplicitSpecifier ES, TypeSourceInfo *TInfo,
2040  SourceLocation LocStart, SourceLocation Loc,
2041  SourceLocation LocEnd) {
2042  DeclarationNameInfo Name(DeductionGuideName, Loc);
2043  ArrayRef<ParmVarDecl *> Params =
2044  TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2045 
2046  // Build the implicit deduction guide template.
2047  auto *Guide =
2048  CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2049  TInfo->getType(), TInfo, LocEnd);
2050  Guide->setImplicit();
2051  Guide->setParams(Params);
2052 
2053  for (auto *Param : Params)
2054  Param->setDeclContext(Guide);
2055 
2056  auto *GuideTemplate = FunctionTemplateDecl::Create(
2057  SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2058  GuideTemplate->setImplicit();
2059  Guide->setDescribedFunctionTemplate(GuideTemplate);
2060 
2061  if (isa<CXXRecordDecl>(DC)) {
2062  Guide->setAccess(AS_public);
2063  GuideTemplate->setAccess(AS_public);
2064  }
2065 
2066  DC->addDecl(GuideTemplate);
2067  return GuideTemplate;
2068  }
2069 };
2070 }
2071 
2073  SourceLocation Loc) {
2074  if (CXXRecordDecl *DefRecord =
2075  cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2076  TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2077  Template = DescribedTemplate ? DescribedTemplate : Template;
2078  }
2079 
2080  DeclContext *DC = Template->getDeclContext();
2081  if (DC->isDependentContext())
2082  return;
2083 
2084  ConvertConstructorToDeductionGuideTransform Transform(
2085  *this, cast<ClassTemplateDecl>(Template));
2086  if (!isCompleteType(Loc, Transform.DeducedType))
2087  return;
2088 
2089  // Check whether we've already declared deduction guides for this template.
2090  // FIXME: Consider storing a flag on the template to indicate this.
2091  auto Existing = DC->lookup(Transform.DeductionGuideName);
2092  for (auto *D : Existing)
2093  if (D->isImplicit())
2094  return;
2095 
2096  // In case we were expanding a pack when we attempted to declare deduction
2097  // guides, turn off pack expansion for everything we're about to do.
2098  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2099  // Create a template instantiation record to track the "instantiation" of
2100  // constructors into deduction guides.
2101  // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2102  // this substitution process actually fail?
2103  InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2104  if (BuildingDeductionGuides.isInvalid())
2105  return;
2106 
2107  // Convert declared constructors into deduction guide templates.
2108  // FIXME: Skip constructors for which deduction must necessarily fail (those
2109  // for which some class template parameter without a default argument never
2110  // appears in a deduced context).
2111  bool AddedAny = false;
2112  for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2113  D = D->getUnderlyingDecl();
2114  if (D->isInvalidDecl() || D->isImplicit())
2115  continue;
2116  D = cast<NamedDecl>(D->getCanonicalDecl());
2117 
2118  auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2119  auto *CD =
2120  dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2121  // Class-scope explicit specializations (MS extension) do not result in
2122  // deduction guides.
2123  if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2124  continue;
2125 
2126  Transform.transformConstructor(FTD, CD);
2127  AddedAny = true;
2128  }
2129 
2130  // C++17 [over.match.class.deduct]
2131  // -- If C is not defined or does not declare any constructors, an
2132  // additional function template derived as above from a hypothetical
2133  // constructor C().
2134  if (!AddedAny)
2135  Transform.buildSimpleDeductionGuide(None);
2136 
2137  // -- An additional function template derived as above from a hypothetical
2138  // constructor C(C), called the copy deduction candidate.
2139  cast<CXXDeductionGuideDecl>(
2140  cast<FunctionTemplateDecl>(
2141  Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2142  ->getTemplatedDecl())
2143  ->setIsCopyDeductionCandidate();
2144 }
2145 
2146 /// Diagnose the presence of a default template argument on a
2147 /// template parameter, which is ill-formed in certain contexts.
2148 ///
2149 /// \returns true if the default template argument should be dropped.
2152  SourceLocation ParamLoc,
2153  SourceRange DefArgRange) {
2154  switch (TPC) {
2156  case Sema::TPC_VarTemplate:
2158  return false;
2159 
2162  // C++ [temp.param]p9:
2163  // A default template-argument shall not be specified in a
2164  // function template declaration or a function template
2165  // definition [...]
2166  // If a friend function template declaration specifies a default
2167  // template-argument, that declaration shall be a definition and shall be
2168  // the only declaration of the function template in the translation unit.
2169  // (C++98/03 doesn't have this wording; see DR226).
2170  S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2171  diag::warn_cxx98_compat_template_parameter_default_in_function_template
2172  : diag::ext_template_parameter_default_in_function_template)
2173  << DefArgRange;
2174  return false;
2175 
2177  // C++0x [temp.param]p9:
2178  // A default template-argument shall not be specified in the
2179  // template-parameter-lists of the definition of a member of a
2180  // class template that appears outside of the member's class.
2181  S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2182  << DefArgRange;
2183  return true;
2184 
2187  // C++ [temp.param]p9:
2188  // A default template-argument shall not be specified in a
2189  // friend template declaration.
2190  S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2191  << DefArgRange;
2192  return true;
2193 
2194  // FIXME: C++0x [temp.param]p9 allows default template-arguments
2195  // for friend function templates if there is only a single
2196  // declaration (and it is a definition). Strange!
2197  }
2198 
2199  llvm_unreachable("Invalid TemplateParamListContext!");
2200 }
2201 
2202 /// Check for unexpanded parameter packs within the template parameters
2203 /// of a template template parameter, recursively.
2205  TemplateTemplateParmDecl *TTP) {
2206  // A template template parameter which is a parameter pack is also a pack
2207  // expansion.
2208  if (TTP->isParameterPack())
2209  return false;
2210 
2212  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2213  NamedDecl *P = Params->getParam(I);
2214  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2215  if (!NTTP->isParameterPack() &&
2216  S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2217  NTTP->getTypeSourceInfo(),
2219  return true;
2220 
2221  continue;
2222  }
2223 
2224  if (TemplateTemplateParmDecl *InnerTTP
2225  = dyn_cast<TemplateTemplateParmDecl>(P))
2226  if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2227  return true;
2228  }
2229 
2230  return false;
2231 }
2232 
2233 /// Checks the validity of a template parameter list, possibly
2234 /// considering the template parameter list from a previous
2235 /// declaration.
2236 ///
2237 /// If an "old" template parameter list is provided, it must be
2238 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2239 /// template parameter list.
2240 ///
2241 /// \param NewParams Template parameter list for a new template
2242 /// declaration. This template parameter list will be updated with any
2243 /// default arguments that are carried through from the previous
2244 /// template parameter list.
2245 ///
2246 /// \param OldParams If provided, template parameter list from a
2247 /// previous declaration of the same template. Default template
2248 /// arguments will be merged from the old template parameter list to
2249 /// the new template parameter list.
2250 ///
2251 /// \param TPC Describes the context in which we are checking the given
2252 /// template parameter list.
2253 ///
2254 /// \param SkipBody If we might have already made a prior merged definition
2255 /// of this template visible, the corresponding body-skipping information.
2256 /// Default argument redefinition is not an error when skipping such a body,
2257 /// because (under the ODR) we can assume the default arguments are the same
2258 /// as the prior merged definition.
2259 ///
2260 /// \returns true if an error occurred, false otherwise.
2262  TemplateParameterList *OldParams,
2264  SkipBodyInfo *SkipBody) {
2265  bool Invalid = false;
2266 
2267  // C++ [temp.param]p10:
2268  // The set of default template-arguments available for use with a
2269  // template declaration or definition is obtained by merging the
2270  // default arguments from the definition (if in scope) and all
2271  // declarations in scope in the same way default function
2272  // arguments are (8.3.6).
2273  bool SawDefaultArgument = false;
2274  SourceLocation PreviousDefaultArgLoc;
2275 
2276  // Dummy initialization to avoid warnings.
2277  TemplateParameterList::iterator OldParam = NewParams->end();
2278  if (OldParams)
2279  OldParam = OldParams->begin();
2280 
2281  bool RemoveDefaultArguments = false;
2282  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2283  NewParamEnd = NewParams->end();
2284  NewParam != NewParamEnd; ++NewParam) {
2285  // Variables used to diagnose redundant default arguments
2286  bool RedundantDefaultArg = false;
2287  SourceLocation OldDefaultLoc;
2288  SourceLocation NewDefaultLoc;
2289 
2290  // Variable used to diagnose missing default arguments
2291  bool MissingDefaultArg = false;
2292 
2293  // Variable used to diagnose non-final parameter packs
2294  bool SawParameterPack = false;
2295 
2296  if (TemplateTypeParmDecl *NewTypeParm
2297  = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2298  // Check the presence of a default argument here.
2299  if (NewTypeParm->hasDefaultArgument() &&
2301  NewTypeParm->getLocation(),
2302  NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2303  .getSourceRange()))
2304  NewTypeParm->removeDefaultArgument();
2305 
2306  // Merge default arguments for template type parameters.
2307  TemplateTypeParmDecl *OldTypeParm
2308  = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2309  if (NewTypeParm->isParameterPack()) {
2310  assert(!NewTypeParm->hasDefaultArgument() &&
2311  "Parameter packs can't have a default argument!");
2312  SawParameterPack = true;
2313  } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2314  NewTypeParm->hasDefaultArgument() &&
2315  (!SkipBody || !SkipBody->ShouldSkip)) {
2316  OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2317  NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2318  SawDefaultArgument = true;
2319  RedundantDefaultArg = true;
2320  PreviousDefaultArgLoc = NewDefaultLoc;
2321  } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2322  // Merge the default argument from the old declaration to the
2323  // new declaration.
2324  NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2325  PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2326  } else if (NewTypeParm->hasDefaultArgument()) {
2327  SawDefaultArgument = true;
2328  PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2329  } else if (SawDefaultArgument)
2330  MissingDefaultArg = true;
2331  } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2332  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2333  // Check for unexpanded parameter packs.
2334  if (!NewNonTypeParm->isParameterPack() &&
2335  DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2336  NewNonTypeParm->getTypeSourceInfo(),
2337  UPPC_NonTypeTemplateParameterType)) {
2338  Invalid = true;
2339  continue;
2340  }
2341 
2342  // Check the presence of a default argument here.
2343  if (NewNonTypeParm->hasDefaultArgument() &&
2345  NewNonTypeParm->getLocation(),
2346  NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2347  NewNonTypeParm->removeDefaultArgument();
2348  }
2349 
2350  // Merge default arguments for non-type template parameters
2351  NonTypeTemplateParmDecl *OldNonTypeParm
2352  = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2353  if (NewNonTypeParm->isParameterPack()) {
2354  assert(!NewNonTypeParm->hasDefaultArgument() &&
2355  "Parameter packs can't have a default argument!");
2356  if (!NewNonTypeParm->isPackExpansion())
2357  SawParameterPack = true;
2358  } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2359  NewNonTypeParm->hasDefaultArgument() &&
2360  (!SkipBody || !SkipBody->ShouldSkip)) {
2361  OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2362  NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2363  SawDefaultArgument = true;
2364  RedundantDefaultArg = true;
2365  PreviousDefaultArgLoc = NewDefaultLoc;
2366  } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2367  // Merge the default argument from the old declaration to the
2368  // new declaration.
2369  NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2370  PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2371  } else if (NewNonTypeParm->hasDefaultArgument()) {
2372  SawDefaultArgument = true;
2373  PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2374  } else if (SawDefaultArgument)
2375  MissingDefaultArg = true;
2376  } else {
2377  TemplateTemplateParmDecl *NewTemplateParm
2378  = cast<TemplateTemplateParmDecl>(*NewParam);
2379 
2380  // Check for unexpanded parameter packs, recursively.
2381  if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2382  Invalid = true;
2383  continue;
2384  }
2385 
2386  // Check the presence of a default argument here.
2387  if (NewTemplateParm->hasDefaultArgument() &&
2389  NewTemplateParm->getLocation(),
2390  NewTemplateParm->getDefaultArgument().getSourceRange()))
2391  NewTemplateParm->removeDefaultArgument();
2392 
2393  // Merge default arguments for template template parameters
2394  TemplateTemplateParmDecl *OldTemplateParm
2395  = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2396  if (NewTemplateParm->isParameterPack()) {
2397  assert(!NewTemplateParm->hasDefaultArgument() &&
2398  "Parameter packs can't have a default argument!");
2399  if (!NewTemplateParm->isPackExpansion())
2400  SawParameterPack = true;
2401  } else if (OldTemplateParm &&
2402  hasVisibleDefaultArgument(OldTemplateParm) &&
2403  NewTemplateParm->hasDefaultArgument() &&
2404  (!SkipBody || !SkipBody->ShouldSkip)) {
2405  OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2406  NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2407  SawDefaultArgument = true;
2408  RedundantDefaultArg = true;
2409  PreviousDefaultArgLoc = NewDefaultLoc;
2410  } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2411  // Merge the default argument from the old declaration to the
2412  // new declaration.
2413  NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2414  PreviousDefaultArgLoc
2415  = OldTemplateParm->getDefaultArgument().getLocation();
2416  } else if (NewTemplateParm->hasDefaultArgument()) {
2417  SawDefaultArgument = true;
2418  PreviousDefaultArgLoc
2419  = NewTemplateParm->getDefaultArgument().getLocation();
2420  } else if (SawDefaultArgument)
2421  MissingDefaultArg = true;
2422  }
2423 
2424  // C++11 [temp.param]p11:
2425  // If a template parameter of a primary class template or alias template
2426  // is a template parameter pack, it shall be the last template parameter.
2427  if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2428  (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2429  TPC == TPC_TypeAliasTemplate)) {
2430  Diag((*NewParam)->getLocation(),
2431  diag::err_template_param_pack_must_be_last_template_parameter);
2432  Invalid = true;
2433  }
2434 
2435  if (RedundantDefaultArg) {
2436  // C++ [temp.param]p12:
2437  // A template-parameter shall not be given default arguments
2438  // by two different declarations in the same scope.
2439  Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2440  Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2441  Invalid = true;
2442  } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2443  // C++ [temp.param]p11:
2444  // If a template-parameter of a class template has a default
2445  // template-argument, each subsequent template-parameter shall either
2446  // have a default template-argument supplied or be a template parameter
2447  // pack.
2448  Diag((*NewParam)->getLocation(),
2449  diag::err_template_param_default_arg_missing);
2450  Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2451  Invalid = true;
2452  RemoveDefaultArguments = true;
2453  }
2454 
2455  // If we have an old template parameter list that we're merging
2456  // in, move on to the next parameter.
2457  if (OldParams)
2458  ++OldParam;
2459  }
2460 
2461  // We were missing some default arguments at the end of the list, so remove
2462  // all of the default arguments.
2463  if (RemoveDefaultArguments) {
2464  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2465  NewParamEnd = NewParams->end();
2466  NewParam != NewParamEnd; ++NewParam) {
2467  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2468  TTP->removeDefaultArgument();
2469  else if (NonTypeTemplateParmDecl *NTTP
2470  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2471  NTTP->removeDefaultArgument();
2472  else
2473  cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2474  }
2475  }
2476 
2477  return Invalid;
2478 }
2479 
2480 namespace {
2481 
2482 /// A class which looks for a use of a certain level of template
2483 /// parameter.
2484 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2486 
2487  unsigned Depth;
2488 
2489  // Whether we're looking for a use of a template parameter that makes the
2490  // overall construct type-dependent / a dependent type. This is strictly
2491  // best-effort for now; we may fail to match at all for a dependent type
2492  // in some cases if this is set.
2493  bool IgnoreNonTypeDependent;
2494 
2495  bool Match;
2496  SourceLocation MatchLoc;
2497 
2498  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2499  : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2500  Match(false) {}
2501 
2502  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2503  : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2504  NamedDecl *ND = Params->getParam(0);
2505  if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2506  Depth = PD->getDepth();
2507  } else if (NonTypeTemplateParmDecl *PD =
2508  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2509  Depth = PD->getDepth();
2510  } else {
2511  Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2512  }
2513  }
2514 
2515  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2516  if (ParmDepth >= Depth) {
2517  Match = true;
2518  MatchLoc = Loc;
2519  return true;
2520  }
2521  return false;
2522  }
2523 
2524  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2525  // Prune out non-type-dependent expressions if requested. This can
2526  // sometimes result in us failing to find a template parameter reference
2527  // (if a value-dependent expression creates a dependent type), but this
2528  // mode is best-effort only.
2529  if (auto *E = dyn_cast_or_null<Expr>(S))
2530  if (IgnoreNonTypeDependent && !E->isTypeDependent())
2531  return true;
2532  return super::TraverseStmt(S, Q);
2533  }
2534 
2535  bool TraverseTypeLoc(TypeLoc TL) {
2536  if (IgnoreNonTypeDependent && !TL.isNull() &&
2537  !TL.getType()->isDependentType())
2538  return true;
2539  return super::TraverseTypeLoc(TL);
2540  }
2541 
2542  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2543  return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2544  }
2545 
2546  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2547  // For a best-effort search, keep looking until we find a location.
2548  return IgnoreNonTypeDependent || !Matches(T->getDepth());
2549  }
2550 
2551  bool TraverseTemplateName(TemplateName N) {
2552  if (TemplateTemplateParmDecl *PD =
2553  dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2554  if (Matches(PD->getDepth()))
2555  return false;
2556  return super::TraverseTemplateName(N);
2557  }
2558 
2559  bool VisitDeclRefExpr(DeclRefExpr *E) {
2560  if (NonTypeTemplateParmDecl *PD =
2561  dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2562  if (Matches(PD->getDepth(), E->getExprLoc()))
2563  return false;
2564  return super::VisitDeclRefExpr(E);
2565  }
2566 
2567  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2568  return TraverseType(T->getReplacementType());
2569  }
2570 
2571  bool
2572  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2573  return TraverseTemplateArgument(T->getArgumentPack());
2574  }
2575 
2576  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2577  return TraverseType(T->getInjectedSpecializationType());
2578  }
2579 };
2580 } // end anonymous namespace
2581 
2582 /// Determines whether a given type depends on the given parameter
2583 /// list.
2584 static bool
2586  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2587  Checker.TraverseType(T);
2588  return Checker.Match;
2589 }
2590 
2591 // Find the source range corresponding to the named type in the given
2592 // nested-name-specifier, if any.
2594  QualType T,
2595  const CXXScopeSpec &SS) {
2597  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2598  if (const Type *CurType = NNS->getAsType()) {
2599  if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2600  return NNSLoc.getTypeLoc().getSourceRange();
2601  } else
2602  break;
2603 
2604  NNSLoc = NNSLoc.getPrefix();
2605  }
2606 
2607  return SourceRange();
2608 }
2609 
2610 /// Match the given template parameter lists to the given scope
2611 /// specifier, returning the template parameter list that applies to the
2612 /// name.
2613 ///
2614 /// \param DeclStartLoc the start of the declaration that has a scope
2615 /// specifier or a template parameter list.
2616 ///
2617 /// \param DeclLoc The location of the declaration itself.
2618 ///
2619 /// \param SS the scope specifier that will be matched to the given template
2620 /// parameter lists. This scope specifier precedes a qualified name that is
2621 /// being declared.
2622 ///
2623 /// \param TemplateId The template-id following the scope specifier, if there
2624 /// is one. Used to check for a missing 'template<>'.
2625 ///
2626 /// \param ParamLists the template parameter lists, from the outermost to the
2627 /// innermost template parameter lists.
2628 ///
2629 /// \param IsFriend Whether to apply the slightly different rules for
2630 /// matching template parameters to scope specifiers in friend
2631 /// declarations.
2632 ///
2633 /// \param IsMemberSpecialization will be set true if the scope specifier
2634 /// denotes a fully-specialized type, and therefore this is a declaration of
2635 /// a member specialization.
2636 ///
2637 /// \returns the template parameter list, if any, that corresponds to the
2638 /// name that is preceded by the scope specifier @p SS. This template
2639 /// parameter list may have template parameters (if we're declaring a
2640 /// template) or may have no template parameters (if we're declaring a
2641 /// template specialization), or may be NULL (if what we're declaring isn't
2642 /// itself a template).
2644  SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2645  TemplateIdAnnotation *TemplateId,
2646  ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2647  bool &IsMemberSpecialization, bool &Invalid) {
2648  IsMemberSpecialization = false;
2649  Invalid = false;
2650 
2651  // The sequence of nested types to which we will match up the template
2652  // parameter lists. We first build this list by starting with the type named
2653  // by the nested-name-specifier and walking out until we run out of types.
2654  SmallVector<QualType, 4> NestedTypes;
2655  QualType T;
2656  if (SS.getScopeRep()) {
2657  if (CXXRecordDecl *Record
2658  = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2659  T = Context.getTypeDeclType(Record);
2660  else
2661  T = QualType(SS.getScopeRep()->getAsType(), 0);
2662  }
2663 
2664  // If we found an explicit specialization that prevents us from needing
2665  // 'template<>' headers, this will be set to the location of that
2666  // explicit specialization.
2667  SourceLocation ExplicitSpecLoc;
2668 
2669  while (!T.isNull()) {
2670  NestedTypes.push_back(T);
2671 
2672  // Retrieve the parent of a record type.
2673  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2674  // If this type is an explicit specialization, we're done.
2676  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2677  if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2678  Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2679  ExplicitSpecLoc = Spec->getLocation();
2680  break;
2681  }
2682  } else if (Record->getTemplateSpecializationKind()
2684  ExplicitSpecLoc = Record->getLocation();
2685  break;
2686  }
2687 
2688  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2689  T = Context.getTypeDeclType(Parent);
2690  else
2691  T = QualType();
2692  continue;
2693  }
2694 
2695  if (const TemplateSpecializationType *TST
2697  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2698  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2699  T = Context.getTypeDeclType(Parent);
2700  else
2701  T = QualType();
2702  continue;
2703  }
2704  }
2705 
2706  // Look one step prior in a dependent template specialization type.
2707  if (const DependentTemplateSpecializationType *DependentTST
2709  if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2710  T = QualType(NNS->getAsType(), 0);
2711  else
2712  T = QualType();
2713  continue;
2714  }
2715 
2716  // Look one step prior in a dependent name type.
2717  if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2718  if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2719  T = QualType(NNS->getAsType(), 0);
2720  else
2721  T = QualType();
2722  continue;
2723  }
2724 
2725  // Retrieve the parent of an enumeration type.
2726  if (const EnumType *EnumT = T->getAs<EnumType>()) {
2727  // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2728  // check here.
2729  EnumDecl *Enum = EnumT->getDecl();
2730 
2731  // Get to the parent type.
2732  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2733  T = Context.getTypeDeclType(Parent);
2734  else
2735  T = QualType();
2736  continue;
2737  }
2738 
2739  T = QualType();
2740  }
2741  // Reverse the nested types list, since we want to traverse from the outermost
2742  // to the innermost while checking template-parameter-lists.
2743  std::reverse(NestedTypes.begin(), NestedTypes.end());
2744 
2745  // C++0x [temp.expl.spec]p17:
2746  // A member or a member template may be nested within many
2747  // enclosing class templates. In an explicit specialization for
2748  // such a member, the member declaration shall be preceded by a
2749  // template<> for each enclosing class template that is
2750  // explicitly specialized.
2751  bool SawNonEmptyTemplateParameterList = false;
2752 
2753  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2754  if (SawNonEmptyTemplateParameterList) {
2755  Diag(DeclLoc, diag::err_specialize_member_of_template)
2756  << !Recovery << Range;
2757  Invalid = true;
2758  IsMemberSpecialization = false;
2759  return true;
2760  }
2761 
2762  return false;
2763  };
2764 
2765  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2766  // Check that we can have an explicit specialization here.
2767  if (CheckExplicitSpecialization(Range, true))
2768  return true;
2769 
2770  // We don't have a template header, but we should.
2771  SourceLocation ExpectedTemplateLoc;
2772  if (!ParamLists.empty())
2773  ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2774  else
2775  ExpectedTemplateLoc = DeclStartLoc;
2776 
2777  Diag(DeclLoc, diag::err_template_spec_needs_header)
2778  << Range
2779  << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2780  return false;
2781  };
2782 
2783  unsigned ParamIdx = 0;
2784  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2785  ++TypeIdx) {
2786  T = NestedTypes[TypeIdx];
2787 
2788  // Whether we expect a 'template<>' header.
2789  bool NeedEmptyTemplateHeader = false;
2790 
2791  // Whether we expect a template header with parameters.
2792  bool NeedNonemptyTemplateHeader = false;
2793 
2794  // For a dependent type, the set of template parameters that we
2795  // expect to see.
2796  TemplateParameterList *ExpectedTemplateParams = nullptr;
2797 
2798  // C++0x [temp.expl.spec]p15:
2799  // A member or a member template may be nested within many enclosing
2800  // class templates. In an explicit specialization for such a member, the
2801  // member declaration shall be preceded by a template<> for each
2802  // enclosing class template that is explicitly specialized.
2803  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2805  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2806  ExpectedTemplateParams = Partial->getTemplateParameters();
2807  NeedNonemptyTemplateHeader = true;
2808  } else if (Record->isDependentType()) {
2809  if (Record->getDescribedClassTemplate()) {
2810  ExpectedTemplateParams = Record->getDescribedClassTemplate()
2811  ->getTemplateParameters();
2812  NeedNonemptyTemplateHeader = true;
2813  }
2814  } else if (ClassTemplateSpecializationDecl *Spec
2815  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2816  // C++0x [temp.expl.spec]p4:
2817  // Members of an explicitly specialized class template are defined
2818  // in the same manner as members of normal classes, and not using
2819  // the template<> syntax.
2820  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2821  NeedEmptyTemplateHeader = true;
2822  else
2823  continue;
2824  } else if (Record->getTemplateSpecializationKind()) {
2825  if (Record->getTemplateSpecializationKind()
2827  TypeIdx == NumTypes - 1)
2828  IsMemberSpecialization = true;
2829 
2830  continue;
2831  }
2832  } else if (const TemplateSpecializationType *TST
2834  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2835  ExpectedTemplateParams = Template->getTemplateParameters();
2836  NeedNonemptyTemplateHeader = true;
2837  }
2838  } else if (T->getAs<DependentTemplateSpecializationType>()) {
2839  // FIXME: We actually could/should check the template arguments here
2840  // against the corresponding template parameter list.
2841  NeedNonemptyTemplateHeader = false;
2842  }
2843 
2844  // C++ [temp.expl.spec]p16:
2845  // In an explicit specialization declaration for a member of a class
2846  // template or a member template that ap- pears in namespace scope, the
2847  // member template and some of its enclosing class templates may remain
2848  // unspecialized, except that the declaration shall not explicitly
2849  // specialize a class member template if its en- closing class templates
2850  // are not explicitly specialized as well.
2851  if (ParamIdx < ParamLists.size()) {
2852  if (ParamLists[ParamIdx]->size() == 0) {
2853  if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2854  false))
2855  return nullptr;
2856  } else
2857  SawNonEmptyTemplateParameterList = true;
2858  }
2859 
2860  if (NeedEmptyTemplateHeader) {
2861  // If we're on the last of the types, and we need a 'template<>' header
2862  // here, then it's a member specialization.
2863  if (TypeIdx == NumTypes - 1)
2864  IsMemberSpecialization = true;
2865 
2866  if (ParamIdx < ParamLists.size()) {
2867  if (ParamLists[ParamIdx]->size() > 0) {
2868  // The header has template parameters when it shouldn't. Complain.
2869  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2870  diag::err_template_param_list_matches_nontemplate)
2871  << T
2872  << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2873  ParamLists[ParamIdx]->getRAngleLoc())
2874  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2875  Invalid = true;
2876  return nullptr;
2877  }
2878 
2879  // Consume this template header.
2880  ++ParamIdx;
2881  continue;
2882  }
2883 
2884  if (!IsFriend)
2885  if (DiagnoseMissingExplicitSpecialization(
2886  getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2887  return nullptr;
2888 
2889  continue;
2890  }
2891 
2892  if (NeedNonemptyTemplateHeader) {
2893  // In friend declarations we can have template-ids which don't
2894  // depend on the corresponding template parameter lists. But
2895  // assume that empty parameter lists are supposed to match this
2896  // template-id.
2897  if (IsFriend && T->isDependentType()) {
2898  if (ParamIdx < ParamLists.size() &&
2899  DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2900  ExpectedTemplateParams = nullptr;
2901  else
2902  continue;
2903  }
2904 
2905  if (ParamIdx < ParamLists.size()) {
2906  // Check the template parameter list, if we can.
2907  if (ExpectedTemplateParams &&
2908  !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2909  ExpectedTemplateParams,
2910  true, TPL_TemplateMatch))
2911  Invalid = true;
2912 
2913  if (!Invalid &&
2914  CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2915  TPC_ClassTemplateMember))
2916  Invalid = true;
2917 
2918  ++ParamIdx;
2919  continue;
2920  }
2921 
2922  Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2923  << T
2924  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2925  Invalid = true;
2926  continue;
2927  }
2928  }
2929 
2930  // If there were at least as many template-ids as there were template
2931  // parameter lists, then there are no template parameter lists remaining for
2932  // the declaration itself.
2933  if (ParamIdx >= ParamLists.size()) {
2934  if (TemplateId && !IsFriend) {
2935  // We don't have a template header for the declaration itself, but we
2936  // should.
2937  DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2938  TemplateId->RAngleLoc));
2939 
2940  // Fabricate an empty template parameter list for the invented header.
2942  SourceLocation(), None,
2943  SourceLocation(), nullptr);
2944  }
2945 
2946  return nullptr;
2947  }
2948 
2949  // If there were too many template parameter lists, complain about that now.
2950  if (ParamIdx < ParamLists.size() - 1) {
2951  bool HasAnyExplicitSpecHeader = false;
2952  bool AllExplicitSpecHeaders = true;
2953  for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2954  if (ParamLists[I]->size() == 0)
2955  HasAnyExplicitSpecHeader = true;
2956  else
2957  AllExplicitSpecHeaders = false;
2958  }
2959 
2960  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2961  AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2962  : diag::err_template_spec_extra_headers)
2963  << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2964  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2965 
2966  // If there was a specialization somewhere, such that 'template<>' is
2967  // not required, and there were any 'template<>' headers, note where the
2968  // specialization occurred.
2969  if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2970  Diag(ExplicitSpecLoc,
2971  diag::note_explicit_template_spec_does_not_need_header)
2972  << NestedTypes.back();
2973 
2974  // We have a template parameter list with no corresponding scope, which
2975  // means that the resulting template declaration can't be instantiated
2976  // properly (we'll end up with dependent nodes when we shouldn't).
2977  if (!AllExplicitSpecHeaders)
2978  Invalid = true;
2979  }
2980 
2981  // C++ [temp.expl.spec]p16:
2982  // In an explicit specialization declaration for a member of a class
2983  // template or a member template that ap- pears in namespace scope, the
2984  // member template and some of its enclosing class templates may remain
2985  // unspecialized, except that the declaration shall not explicitly
2986  // specialize a class member template if its en- closing class templates
2987  // are not explicitly specialized as well.
2988  if (ParamLists.back()->size() == 0 &&
2989  CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2990  false))
2991  return nullptr;
2992 
2993  // Return the last template parameter list, which corresponds to the
2994  // entity being declared.
2995  return ParamLists.back();
2996 }
2997 
2999  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3000  Diag(Template->getLocation(), diag::note_template_declared_here)
3001  << (isa<FunctionTemplateDecl>(Template)
3002  ? 0
3003  : isa<ClassTemplateDecl>(Template)
3004  ? 1
3005  : isa<VarTemplateDecl>(Template)
3006  ? 2
3007  : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3008  << Template->getDeclName();
3009  return;
3010  }
3011 
3013  for (OverloadedTemplateStorage::iterator I = OST->begin(),
3014  IEnd = OST->end();
3015  I != IEnd; ++I)
3016  Diag((*I)->getLocation(), diag::note_template_declared_here)
3017  << 0 << (*I)->getDeclName();
3018 
3019  return;
3020  }
3021 }
3022 
3023 static QualType
3025  const SmallVectorImpl<TemplateArgument> &Converted,
3026  SourceLocation TemplateLoc,
3027  TemplateArgumentListInfo &TemplateArgs) {
3028  ASTContext &Context = SemaRef.getASTContext();
3029  switch (BTD->getBuiltinTemplateKind()) {
3030  case BTK__make_integer_seq: {
3031  // Specializations of __make_integer_seq<S, T, N> are treated like
3032  // S<T, 0, ..., N-1>.
3033 
3034  // C++14 [inteseq.intseq]p1:
3035  // T shall be an integer type.
3036  if (!Converted[1].getAsType()->isIntegralType(Context)) {
3037  SemaRef.Diag(TemplateArgs[1].getLocation(),
3038  diag::err_integer_sequence_integral_element_type);
3039  return QualType();
3040  }
3041 
3042  // C++14 [inteseq.make]p1:
3043  // If N is negative the program is ill-formed.
3044  TemplateArgument NumArgsArg = Converted[2];
3045  llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3046  if (NumArgs < 0) {
3047  SemaRef.Diag(TemplateArgs[2].getLocation(),
3048  diag::err_integer_sequence_negative_length);
3049  return QualType();
3050  }
3051 
3052  QualType ArgTy = NumArgsArg.getIntegralType();
3053  TemplateArgumentListInfo SyntheticTemplateArgs;
3054  // The type argument gets reused as the first template argument in the
3055  // synthetic template argument list.
3056  SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3057  // Expand N into 0 ... N-1.
3058  for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3059  I < NumArgs; ++I) {
3060  TemplateArgument TA(Context, I, ArgTy);
3061  SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3062  TA, ArgTy, TemplateArgs[2].getLocation()));
3063  }
3064  // The first template argument will be reused as the template decl that
3065  // our synthetic template arguments will be applied to.
3066  return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3067  TemplateLoc, SyntheticTemplateArgs);
3068  }
3069 
3071  // Specializations of
3072  // __type_pack_element<Index, T_1, ..., T_N>
3073  // are treated like T_Index.
3074  assert(Converted.size() == 2 &&
3075  "__type_pack_element should be given an index and a parameter pack");
3076 
3077  // If the Index is out of bounds, the program is ill-formed.
3078  TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3079  llvm::APSInt Index = IndexArg.getAsIntegral();
3080  assert(Index >= 0 && "the index used with __type_pack_element should be of "
3081  "type std::size_t, and hence be non-negative");
3082  if (Index >= Ts.pack_size()) {
3083  SemaRef.Diag(TemplateArgs[0].getLocation(),
3084  diag::err_type_pack_element_out_of_bounds);
3085  return QualType();
3086  }
3087 
3088  // We simply return the type at index `Index`.
3089  auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3090  return Nth->getAsType();
3091  }
3092  llvm_unreachable("unexpected BuiltinTemplateDecl!");
3093 }
3094 
3095 /// Determine whether this alias template is "enable_if_t".
3096 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3097  return AliasTemplate->getName().equals("enable_if_t");
3098 }
3099 
3100 /// Collect all of the separable terms in the given condition, which
3101 /// might be a conjunction.
3102 ///
3103 /// FIXME: The right answer is to convert the logical expression into
3104 /// disjunctive normal form, so we can find the first failed term
3105 /// within each possible clause.
3106 static void collectConjunctionTerms(Expr *Clause,
3107  SmallVectorImpl<Expr *> &Terms) {
3108  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3109  if (BinOp->getOpcode() == BO_LAnd) {
3110  collectConjunctionTerms(BinOp->getLHS(), Terms);
3111  collectConjunctionTerms(BinOp->getRHS(), Terms);
3112  }
3113 
3114  return;
3115  }
3116 
3117  Terms.push_back(Clause);
3118 }
3119 
3120 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3121 // a left-hand side that is value-dependent but never true. Identify
3122 // the idiom and ignore that term.
3124  // Top-level '||'.
3125  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3126  if (!BinOp) return Cond;
3127 
3128  if (BinOp->getOpcode() != BO_LOr) return Cond;
3129 
3130  // With an inner '==' that has a literal on the right-hand side.
3131  Expr *LHS = BinOp->getLHS();
3132  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3133  if (!InnerBinOp) return Cond;
3134 
3135  if (InnerBinOp->getOpcode() != BO_EQ ||
3136  !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3137  return Cond;
3138 
3139  // If the inner binary operation came from a macro expansion named
3140  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3141  // of the '||', which is the real, user-provided condition.
3142  SourceLocation Loc = InnerBinOp->getExprLoc();
3143  if (!Loc.isMacroID()) return Cond;
3144 
3145  StringRef MacroName = PP.getImmediateMacroName(Loc);
3146  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3147  return BinOp->getRHS();
3148 
3149  return Cond;
3150 }
3151 
3152 namespace {
3153 
3154 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3155 // within failing boolean expression, such as substituting template parameters
3156 // for actual types.
3157 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3158 public:
3159  explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3160  : Policy(P) {}
3161 
3162  bool handledStmt(Stmt *E, raw_ostream &OS) override {
3163  const auto *DR = dyn_cast<DeclRefExpr>(E);
3164  if (DR && DR->getQualifier()) {
3165  // If this is a qualified name, expand the template arguments in nested
3166  // qualifiers.
3167  DR->getQualifier()->print(OS, Policy, true);
3168  // Then print the decl itself.
3169  const ValueDecl *VD = DR->getDecl();
3170  OS << VD->getName();
3171  if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3172  // This is a template variable, print the expanded template arguments.
3173  printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3174  }
3175  return true;
3176  }
3177  return false;
3178  }
3179 
3180 private:
3181  const PrintingPolicy Policy;
3182 };
3183 
3184 } // end anonymous namespace
3185 
3186 std::pair<Expr *, std::string>
3188  Cond = lookThroughRangesV3Condition(PP, Cond);
3189 
3190  // Separate out all of the terms in a conjunction.
3191  SmallVector<Expr *, 4> Terms;
3192  collectConjunctionTerms(Cond, Terms);
3193 
3194  // Determine which term failed.
3195  Expr *FailedCond = nullptr;
3196  for (Expr *Term : Terms) {
3197  Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3198 
3199  // Literals are uninteresting.
3200  if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3201  isa<IntegerLiteral>(TermAsWritten))
3202  continue;
3203 
3204  // The initialization of the parameter from the argument is
3205  // a constant-evaluated context.
3206  EnterExpressionEvaluationContext ConstantEvaluated(
3208 
3209  bool Succeeded;
3210  if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3211  !Succeeded) {
3212  FailedCond = TermAsWritten;
3213  break;
3214  }
3215  }
3216  if (!FailedCond)
3217  FailedCond = Cond->IgnoreParenImpCasts();
3218 
3219  std::string Description;
3220  {
3221  llvm::raw_string_ostream Out(Description);
3222  PrintingPolicy Policy = getPrintingPolicy();
3223  Policy.PrintCanonicalTypes = true;
3224  FailedBooleanConditionPrinterHelper Helper(Policy);
3225  FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3226  }
3227  return { FailedCond, Description };
3228 }
3229 
3231  SourceLocation TemplateLoc,
3232  TemplateArgumentListInfo &TemplateArgs) {
3235  if (DTN && DTN->isIdentifier())
3236  // When building a template-id where the template-name is dependent,
3237  // assume the template is a type template. Either our assumption is
3238  // correct, or the code is ill-formed and will be diagnosed when the
3239  // dependent name is substituted.
3241  DTN->getQualifier(),
3242  DTN->getIdentifier(),
3243  TemplateArgs);
3244 
3245  TemplateDecl *Template = Name.getAsTemplateDecl();
3246  if (!Template || isa<FunctionTemplateDecl>(Template) ||
3247  isa<VarTemplateDecl>(Template) ||
3248  isa<ConceptDecl>(Template)) {
3249  // We might have a substituted template template parameter pack. If so,
3250  // build a template specialization type for it.
3252  return Context.getTemplateSpecializationType(Name, TemplateArgs);
3253 
3254  Diag(TemplateLoc, diag::err_template_id_not_a_type)
3255  << Name;
3256  NoteAllFoundTemplates(Name);
3257  return QualType();
3258  }
3259 
3260  // Check that the template argument list is well-formed for this
3261  // template.
3263  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3264  false, Converted))
3265  return QualType();
3266 
3267  QualType CanonType;
3268 
3269  bool InstantiationDependent = false;
3270  if (TypeAliasTemplateDecl *AliasTemplate =
3271  dyn_cast<TypeAliasTemplateDecl>(Template)) {
3272  // Find the canonical type for this type alias template specialization.
3273  TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3274  if (Pattern->isInvalidDecl())
3275  return QualType();
3276 
3278  Converted);
3279 
3280  // Only substitute for the innermost template argument list.
3281  MultiLevelTemplateArgumentList TemplateArgLists;
3282  TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3283  unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3284  for (unsigned I = 0; I < Depth; ++I)
3285  TemplateArgLists.addOuterTemplateArguments(None);
3286 
3288  InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3289  if (Inst.isInvalid())
3290  return QualType();
3291 
3292  CanonType = SubstType(Pattern->getUnderlyingType(),
3293  TemplateArgLists, AliasTemplate->getLocation(),
3294  AliasTemplate->getDeclName());
3295  if (CanonType.isNull()) {
3296  // If this was enable_if and we failed to find the nested type
3297  // within enable_if in a SFINAE context, dig out the specific
3298  // enable_if condition that failed and present that instead.
3299  if (isEnableIfAliasTemplate(AliasTemplate)) {
3300  if (auto DeductionInfo = isSFINAEContext()) {
3301  if (*DeductionInfo &&
3302  (*DeductionInfo)->hasSFINAEDiagnostic() &&
3303  (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3304  diag::err_typename_nested_not_found_enable_if &&
3305  TemplateArgs[0].getArgument().getKind()
3307  Expr *FailedCond;
3308  std::string FailedDescription;
3309  std::tie(FailedCond, FailedDescription) =
3310  findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3311 
3312  // Remove the old SFINAE diagnostic.
3313  PartialDiagnosticAt OldDiag =
3315  (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3316 
3317  // Add a new SFINAE diagnostic specifying which condition
3318  // failed.
3319  (*DeductionInfo)->addSFINAEDiagnostic(
3320  OldDiag.first,
3321  PDiag(diag::err_typename_nested_not_found_requirement)
3322  << FailedDescription
3323  << FailedCond->getSourceRange());
3324  }
3325  }
3326  }
3327 
3328  return QualType();
3329  }
3330  } else if (Name.isDependent() ||
3332  TemplateArgs, InstantiationDependent)) {
3333  // This class template specialization is a dependent
3334  // type. Therefore, its canonical type is another class template
3335  // specialization type that contains all of the converted
3336  // arguments in canonical form. This ensures that, e.g., A<T> and
3337  // A<T, T> have identical types when A is declared as:
3338  //
3339  // template<typename T, typename U = T> struct A;
3340  CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3341 
3342  // This might work out to be a current instantiation, in which
3343  // case the canonical type needs to be the InjectedClassNameType.
3344  //
3345  // TODO: in theory this could be a simple hashtable lookup; most
3346  // changes to CurContext don't change the set of current
3347  // instantiations.
3348  if (isa<ClassTemplateDecl>(Template)) {
3349  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3350  // If we get out to a namespace, we're done.
3351  if (Ctx->isFileContext()) break;
3352 
3353  // If this isn't a record, keep looking.
3354  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3355  if (!Record) continue;
3356 
3357  // Look for one of the two cases with InjectedClassNameTypes
3358  // and check whether it's the same template.
3359  if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3360  !Record->getDescribedClassTemplate())
3361  continue;
3362 
3363  // Fetch the injected class name type and check whether its
3364  // injected type is equal to the type we just built.
3365  QualType ICNT = Context.getTypeDeclType(Record);
3366  QualType Injected = cast<InjectedClassNameType>(ICNT)
3367  ->getInjectedSpecializationType();
3368 
3369  if (CanonType != Injected->getCanonicalTypeInternal())
3370  continue;
3371 
3372  // If so, the canonical type of this TST is the injected
3373  // class name type of the record we just found.
3374  assert(ICNT.isCanonical());
3375  CanonType = ICNT;
3376  break;
3377  }
3378  }
3379  } else if (ClassTemplateDecl *ClassTemplate
3380  = dyn_cast<ClassTemplateDecl>(Template)) {
3381  // Find the class template specialization declaration that
3382  // corresponds to these arguments.
3383  void *InsertPos = nullptr;
3385  = ClassTemplate->findSpecialization(Converted, InsertPos);
3386  if (!Decl) {
3387  // This is the first time we have referenced this class template
3388  // specialization. Create the canonical declaration and add it to
3389  // the set of specializations.
3391  Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3392  ClassTemplate->getDeclContext(),
3393  ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3394  ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3395  ClassTemplate->AddSpecialization(Decl, InsertPos);
3396  if (ClassTemplate->isOutOfLine())
3397  Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3398  }
3399 
3400  if (Decl->getSpecializationKind() == TSK_Undeclared) {
3401  MultiLevelTemplateArgumentList TemplateArgLists;
3402  TemplateArgLists.addOuterTemplateArguments(Converted);
3403  InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3404  Decl);
3405  }
3406 
3407  // Diagnose uses of this specialization.
3408  (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3409 
3410  CanonType = Context.getTypeDeclType(Decl);
3411  assert(isa<RecordType>(CanonType) &&
3412  "type of non-dependent specialization is not a RecordType");
3413  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3414  CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3415  TemplateArgs);
3416  }
3417 
3418  // Build the fully-sugared type for this class template
3419  // specialization, which refers back to the class template
3420  // specialization we created or found.
3421  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3422 }
3423 
3425  TemplateNameKind &TNK,
3426  SourceLocation NameLoc,
3427  IdentifierInfo *&II) {
3428  assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3429 
3430  TemplateName Name = ParsedName.get();
3431  auto *ATN = Name.getAsAssumedTemplateName();
3432  assert(ATN && "not an assumed template name");
3433  II = ATN->getDeclName().getAsIdentifierInfo();
3434 
3435  if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3436  // Resolved to a type template name.
3437  ParsedName = TemplateTy::make(Name);
3438  TNK = TNK_Type_template;
3439  }
3440 }
3441 
3443  SourceLocation NameLoc,
3444  bool Diagnose) {
3445  // We assumed this undeclared identifier to be an (ADL-only) function
3446  // template name, but it was used in a context where a type was required.
3447  // Try to typo-correct it now.
3449  assert(ATN && "not an assumed template name");
3450 
3451  LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3452  struct CandidateCallback : CorrectionCandidateCallback {
3453  bool ValidateCandidate(const TypoCorrection &TC) override {
3454  return TC.getCorrectionDecl() &&
3456  }
3457  std::unique_ptr<CorrectionCandidateCallback> clone() override {
3458  return std::make_unique<CandidateCallback>(*this);
3459  }
3460  } FilterCCC;
3461 
3462  TypoCorrection Corrected =
3463  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3464  FilterCCC, CTK_ErrorRecovery);
3465  if (Corrected && Corrected.getFoundDecl()) {
3466  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3467  << ATN->getDeclName());
3468  Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3469  return false;
3470  }
3471 
3472  if (Diagnose)
3473  Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3474  return true;
3475 }
3476 
3478  Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3479  TemplateTy TemplateD, IdentifierInfo *TemplateII,
3480  SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3481  ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3482  bool IsCtorOrDtorName, bool IsClassName) {
3483  if (SS.isInvalid())
3484  return true;
3485 
3486  if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3487  DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3488 
3489  // C++ [temp.res]p3:
3490  // A qualified-id that refers to a type and in which the
3491  // nested-name-specifier depends on a template-parameter (14.6.2)
3492  // shall be prefixed by the keyword typename to indicate that the
3493  // qualified-id denotes a type, forming an
3494  // elaborated-type-specifier (7.1.5.3).
3495  if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3496  Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3497  << SS.getScopeRep() << TemplateII->getName();
3498  // Recover as if 'typename' were specified.
3499  // FIXME: This is not quite correct recovery as we don't transform SS
3500  // into the corresponding dependent form (and we don't diagnose missing
3501  // 'template' keywords within SS as a result).
3502  return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3503  TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3504  TemplateArgsIn, RAngleLoc);
3505  }
3506 
3507  // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3508  // it's not actually allowed to be used as a type in most cases. Because
3509  // we annotate it before we know whether it's valid, we have to check for
3510  // this case here.
3511  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3512  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3513  Diag(TemplateIILoc,
3514  TemplateKWLoc.isInvalid()
3515  ? diag::err_out_of_line_qualified_id_type_names_constructor
3516  : diag::ext_out_of_line_qualified_id_type_names_constructor)
3517  << TemplateII << 0 /*injected-class-name used as template name*/
3518  << 1 /*if any keyword was present, it was 'template'*/;
3519  }
3520  }
3521 
3522  TemplateName Template = TemplateD.get();
3523  if (Template.getAsAssumedTemplateName() &&
3524  resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3525  return true;
3526 
3527  // Translate the parser's template argument list in our AST format.
3528  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3529  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3530 
3531  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3532  QualType T
3534  DTN->getQualifier(),
3535  DTN->getIdentifier(),
3536  TemplateArgs);
3537  // Build type-source information.
3538  TypeLocBuilder TLB;
3542  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3543  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3544  SpecTL.setTemplateNameLoc(TemplateIILoc);
3545  SpecTL.setLAngleLoc(LAngleLoc);
3546  SpecTL.setRAngleLoc(RAngleLoc);
3547  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3548  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3549  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3550  }
3551 
3552  QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3553  if (Result.isNull())
3554  return true;
3555 
3556  // Build type-source information.
3557  TypeLocBuilder TLB;
3559  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3560  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3561  SpecTL.setTemplateNameLoc(TemplateIILoc);
3562  SpecTL.setLAngleLoc(LAngleLoc);
3563  SpecTL.setRAngleLoc(RAngleLoc);
3564  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3565  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3566 
3567  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3568  // constructor or destructor name (in such a case, the scope specifier
3569  // will be attached to the enclosing Decl or Expr node).
3570  if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3571  // Create an elaborated-type-specifier containing the nested-name-specifier.
3572  Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3573  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3575  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3576  }
3577 
3578  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3579 }
3580 
3582  TypeSpecifierType TagSpec,
3583  SourceLocation TagLoc,
3584  CXXScopeSpec &SS,
3585  SourceLocation TemplateKWLoc,
3586  TemplateTy TemplateD,
3587  SourceLocation TemplateLoc,
3588  SourceLocation LAngleLoc,
3589  ASTTemplateArgsPtr TemplateArgsIn,
3590  SourceLocation RAngleLoc) {
3591  TemplateName Template = TemplateD.get();
3592 
3593  // Translate the parser's template argument list in our AST format.
3594  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3595  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3596 
3597  // Determine the tag kind
3599  ElaboratedTypeKeyword Keyword
3601 
3602  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3604  DTN->getQualifier(),
3605  DTN->getIdentifier(),
3606  TemplateArgs);
3607 
3608  // Build type-source information.
3609  TypeLocBuilder TLB;
3612  SpecTL.setElaboratedKeywordLoc(TagLoc);
3613  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3614  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3615  SpecTL.setTemplateNameLoc(TemplateLoc);
3616  SpecTL.setLAngleLoc(LAngleLoc);
3617  SpecTL.setRAngleLoc(RAngleLoc);
3618  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3619  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3620  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3621  }
3622 
3623  if (TypeAliasTemplateDecl *TAT =
3624  dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3625  // C++0x [dcl.type.elab]p2:
3626  // If the identifier resolves to a typedef-name or the simple-template-id
3627  // resolves to an alias template specialization, the
3628  // elaborated-type-specifier is ill-formed.
3629  Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3630  << TAT << NTK_TypeAliasTemplate << TagKind;
3631  Diag(TAT->getLocation(), diag::note_declared_at);
3632  }
3633 
3634  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3635  if (Result.isNull())
3636  return TypeResult(true);
3637 
3638  // Check the tag kind
3639  if (const RecordType *RT = Result->getAs<RecordType>()) {
3640  RecordDecl *D = RT->getDecl();
3641 
3643  assert(Id && "templated class must have an identifier");
3644 
3645  if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3646  TagLoc, Id)) {
3647  Diag(TagLoc, diag::err_use_with_wrong_tag)
3648  << Result
3650  Diag(D->getLocation(), diag::note_previous_use);
3651  }
3652  }
3653 
3654  // Provide source-location information for the template specialization.
3655  TypeLocBuilder TLB;
3657  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3658  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3659  SpecTL.setTemplateNameLoc(TemplateLoc);
3660  SpecTL.setLAngleLoc(LAngleLoc);
3661  SpecTL.setRAngleLoc(RAngleLoc);
3662  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3663  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3664 
3665  // Construct an elaborated type containing the nested-name-specifier (if any)
3666  // and tag keyword.
3667  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3668  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3669  ElabTL.setElaboratedKeywordLoc(TagLoc);
3670  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3671  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3672 }
3673 
3674 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3675  NamedDecl *PrevDecl,
3676  SourceLocation Loc,
3678 
3680 
3682  const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3683  switch (Arg.getKind()) {
3690  return false;
3691 
3692  case TemplateArgument::Type: {
3693  QualType Type = Arg.getAsType();
3694  const TemplateTypeParmType *TPT =
3696  return TPT && !Type.hasQualifiers() &&
3697  TPT->getDepth() == Depth && TPT->getIndex() == Index;
3698  }
3699 
3701  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3702  if (!DRE || !DRE->getDecl())
3703  return false;
3704  const NonTypeTemplateParmDecl *NTTP =
3705  dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3706  return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3707  }
3708 
3710  const TemplateTemplateParmDecl *TTP =
3711  dyn_cast_or_null<TemplateTemplateParmDecl>(
3713  return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3714  }
3715  llvm_unreachable("unexpected kind of template argument");
3716 }
3717 
3720  if (Params->size() != Args.size())
3721  return false;
3722 
3723  unsigned Depth = Params->getDepth();
3724 
3725  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3726  TemplateArgument Arg = Args[I];
3727 
3728  // If the parameter is a pack expansion, the argument must be a pack
3729  // whose only element is a pack expansion.
3730  if (Params->getParam(I)->isParameterPack()) {
3731  if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3732  !Arg.pack_begin()->isPackExpansion())
3733  return false;
3734  Arg = Arg.pack_begin()->getPackExpansionPattern();
3735  }
3736 
3737  if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3738  return false;
3739  }
3740 
3741  return true;
3742 }
3743 
3744 /// Convert the parser's template argument list representation into our form.
3747  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3748  TemplateId.RAngleLoc);
3749  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3750  TemplateId.NumArgs);
3751  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3752  return TemplateArgs;
3753 }
3754 
3755 template<typename PartialSpecDecl>
3756 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3757  if (Partial->getDeclContext()->isDependentContext())
3758  return;
3759 
3760  // FIXME: Get the TDK from deduction in order to provide better diagnostics
3761  // for non-substitution-failure issues?
3762  TemplateDeductionInfo Info(Partial->getLocation());
3763  if (S.isMoreSpecializedThanPrimary(Partial, Info))
3764  return;
3765 
3766  auto *Template = Partial->getSpecializedTemplate();
3767  S.Diag(Partial->getLocation(),
3768  diag::ext_partial_spec_not_more_specialized_than_primary)
3769  << isa<VarTemplateDecl>(Template);
3770 
3771  if (Info.hasSFINAEDiagnostic()) {
3774  Info.takeSFINAEDiagnostic(Diag);
3775  SmallString<128> SFINAEArgString;
3776  Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3777  S.Diag(Diag.first,
3778  diag::note_partial_spec_not_more_specialized_than_primary)
3779  << SFINAEArgString;
3780  }
3781 
3782  S.Diag(Template->getLocation(), diag::note_template_decl_here);
3783 }
3784 
3785 static void
3787  const llvm::SmallBitVector &DeducibleParams) {
3788  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3789  if (!DeducibleParams[I]) {
3790  NamedDecl *Param = TemplateParams->getParam(I);
3791  if (Param->getDeclName())
3792  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3793  << Param->getDeclName();
3794  else
3795  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3796  << "(anonymous)";
3797  }
3798  }
3799 }
3800 
3801 
3802 template<typename PartialSpecDecl>
3804  PartialSpecDecl *Partial) {
3805  // C++1z [temp.class.spec]p8: (DR1495)
3806  // - The specialization shall be more specialized than the primary
3807  // template (14.5.5.2).
3808  checkMoreSpecializedThanPrimary(S, Partial);
3809 
3810  // C++ [temp.class.spec]p8: (DR1315)
3811  // - Each template-parameter shall appear at least once in the
3812  // template-id outside a non-deduced context.
3813  // C++1z [temp.class.spec.match]p3 (P0127R2)
3814  // If the template arguments of a partial specialization cannot be
3815  // deduced because of the structure of its template-parameter-list
3816  // and the template-id, the program is ill-formed.
3817  auto *TemplateParams = Partial->getTemplateParameters();
3818  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3819  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3820  TemplateParams->getDepth(), DeducibleParams);
3821 
3822  if (!DeducibleParams.all()) {
3823  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3824  S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3825  << isa<VarTemplatePartialSpecializationDecl>(Partial)
3826  << (NumNonDeducible > 1)
3827  << SourceRange(Partial->getLocation(),
3828  Partial->getTemplateArgsAsWritten()->RAngleLoc);
3829  noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3830  }
3831 }
3832 
3835  checkTemplatePartialSpecialization(*this, Partial);
3836 }
3837 
3840  checkTemplatePartialSpecialization(*this, Partial);
3841 }
3842 
3844  // C++1z [temp.param]p11:
3845  // A template parameter of a deduction guide template that does not have a
3846  // default-argument shall be deducible from the parameter-type-list of the
3847  // deduction guide template.
3848  auto *TemplateParams = TD->getTemplateParameters();
3849  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3850  MarkDeducedTemplateParameters(TD, DeducibleParams);
3851  for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3852  // A parameter pack is deducible (to an empty pack).
3853  auto *Param = TemplateParams->getParam(I);
3854  if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3855  DeducibleParams[I] = true;
3856  }
3857 
3858  if (!DeducibleParams.all()) {
3859  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3860  Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3861  << (NumNonDeducible > 1);
3862  noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3863  }
3864 }
3865 
3867  Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3868  TemplateParameterList *TemplateParams, StorageClass SC,
3869  bool IsPartialSpecialization) {
3870  // D must be variable template id.
3872  "Variable template specialization is declared with a template it.");
3873 
3874  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3875  TemplateArgumentListInfo TemplateArgs =
3876  makeTemplateArgumentListInfo(*this, *TemplateId);
3877  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3878  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3879  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3880 
3881  TemplateName Name = TemplateId->Template.get();
3882 
3883  // The template-id must name a variable template.
3884  VarTemplateDecl *VarTemplate =
3885  dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3886  if (!VarTemplate) {
3887  NamedDecl *FnTemplate;
3888  if (auto *OTS = Name.getAsOverloadedTemplate())
3889  FnTemplate = *OTS->begin();
3890  else
3891  FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3892  if (FnTemplate)
3893  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3894  << FnTemplate->getDeclName();
3895  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3896  << IsPartialSpecialization;
3897  }
3898 
3899  // Check for unexpanded parameter packs in any of the template arguments.
3900  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3901  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3902  UPPC_PartialSpecialization))
3903  return true;
3904 
3905  // Check that the template argument list is well-formed for this
3906  // template.
3908  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3909  false, Converted))
3910  return true;
3911 
3912  // Find the variable template (partial) specialization declaration that
3913  // corresponds to these arguments.
3914  if (IsPartialSpecialization) {
3915  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3916  TemplateArgs.size(), Converted))
3917  return true;
3918 
3919  // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3920  // also do them during instantiation.
3921  bool InstantiationDependent;
3922  if (!Name.isDependent() &&
3924  TemplateArgs.arguments(),
3925  InstantiationDependent)) {
3926  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3927  << VarTemplate->getDeclName();
3928  IsPartialSpecialization = false;
3929  }
3930 
3932  Converted)) {
3933  // C++ [temp.class.spec]p9b3:
3934  //
3935  // -- The argument list of the specialization shall not be identical
3936  // to the implicit argument list of the primary template.
3937  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3938  << /*variable template*/ 1
3939  << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3940  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3941  // FIXME: Recover from this by treating the declaration as a redeclaration
3942  // of the primary template.
3943  return true;
3944  }
3945  }
3946 
3947  void *InsertPos = nullptr;
3948  VarTemplateSpecializationDecl *PrevDecl = nullptr;
3949 
3950  if (IsPartialSpecialization)
3951  // FIXME: Template parameter list matters too
3952  PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3953  else
3954  PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3955 
3956  VarTemplateSpecializationDecl *Specialization = nullptr;
3957 
3958  // Check whether we can declare a variable template specialization in
3959  // the current scope.
3960  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3961  TemplateNameLoc,
3962  IsPartialSpecialization))
3963  return true;
3964 
3965  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3966  // Since the only prior variable template specialization with these
3967  // arguments was referenced but not declared, reuse that
3968  // declaration node as our own, updating its source location and
3969  // the list of outer template parameters to reflect our new declaration.
3970  Specialization = PrevDecl;
3971  Specialization->setLocation(TemplateNameLoc);
3972  PrevDecl = nullptr;
3973  } else if (IsPartialSpecialization) {
3974  // Create a new class template partial specialization declaration node.
3976  cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3979  Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3980  TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3981  Converted, TemplateArgs);
3982 
3983  if (!PrevPartial)
3984  VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3985  Specialization = Partial;
3986 
3987  // If we are providing an explicit specialization of a member variable
3988  // template specialization, make a note of that.
3989  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3990  PrevPartial->setMemberSpecialization();
3991 
3992  CheckTemplatePartialSpecialization(Partial);
3993  } else {
3994  // Create a new class template specialization declaration node for
3995  // this explicit specialization or friend declaration.
3996  Specialization = VarTemplateSpecializationDecl::Create(
3997  Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3998  VarTemplate, DI->getType(), DI, SC, Converted);
3999  Specialization->setTemplateArgsInfo(TemplateArgs);
4000 
4001  if (!PrevDecl)
4002  VarTemplate->AddSpecialization(Specialization, InsertPos);
4003  }
4004 
4005  // C++ [temp.expl.spec]p6:
4006  // If a template, a member template or the member of a class template is
4007  // explicitly specialized then that specialization shall be declared
4008  // before the first use of that specialization that would cause an implicit
4009  // instantiation to take place, in every translation unit in which such a
4010  // use occurs; no diagnostic is required.
4011  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4012  bool Okay = false;
4013  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4014  // Is there any previous explicit specialization declaration?
4016  Okay = true;
4017  break;
4018  }
4019  }
4020 
4021  if (!Okay) {
4022  SourceRange Range(TemplateNameLoc, RAngleLoc);
4023  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4024  << Name << Range;
4025 
4026  Diag(PrevDecl->getPointOfInstantiation(),
4027  diag::note_instantiation_required_here)
4028  << (PrevDecl->getTemplateSpecializationKind() !=
4030  return true;
4031  }
4032  }
4033 
4034  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4035  Specialization->setLexicalDeclContext(CurContext);
4036 
4037  // Add the specialization into its lexical context, so that it can
4038  // be seen when iterating through the list of declarations in that
4039  // context. However, specializations are not found by name lookup.
4040  CurContext->addDecl(Specialization);
4041 
4042  // Note that this is an explicit specialization.
4044 
4045  if (PrevDecl) {
4046  // Check that this isn't a redefinition of this specialization,
4047  // merging with previous declarations.
4048  LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4049  forRedeclarationInCurContext());
4050  PrevSpec.addDecl(PrevDecl);
4051  D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4052  } else if (Specialization->isStaticDataMember() &&
4053  Specialization->isOutOfLine()) {
4054  Specialization->setAccess(VarTemplate->getAccess());
4055  }
4056 
4057  return Specialization;
4058 }
4059 
4060 namespace {
4061 /// A partial specialization whose template arguments have matched
4062 /// a given template-id.
4063 struct PartialSpecMatchResult {
4065  TemplateArgumentList *Args;
4066 };
4067 } // end anonymous namespace
4068 
4069 DeclResult
4071  SourceLocation TemplateNameLoc,
4072  const TemplateArgumentListInfo &TemplateArgs) {
4073  assert(Template && "A variable template id without template?");
4074 
4075  // Check that the template argument list is well-formed for this template.
4077  if (CheckTemplateArgumentList(
4078  Template, TemplateNameLoc,
4079  const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4080  Converted))
4081  return true;
4082 
4083  // Find the variable template specialization declaration that
4084  // corresponds to these arguments.
4085  void *InsertPos = nullptr;
4086  if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4087  Converted, InsertPos)) {
4088  checkSpecializationVisibility(TemplateNameLoc, Spec);
4089  // If we already have a variable template specialization, return it.
4090  return Spec;
4091  }
4092 
4093  // This is the first time we have referenced this variable template
4094  // specialization. Create the canonical declaration and add it to
4095  // the set of specializations, based on the closest partial specialization
4096  // that it represents. That is,
4097  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4099  Converted);
4100  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4101  bool AmbiguousPartialSpec = false;
4102  typedef PartialSpecMatchResult MatchResult;
4104  SourceLocation PointOfInstantiation = TemplateNameLoc;
4105  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4106  /*ForTakingAddress=*/false);
4107 
4108  // 1. Attempt to find the closest partial specialization that this
4109  // specializes, if any.
4110  // If any of the template arguments is dependent, then this is probably
4111  // a placeholder for an incomplete declarative context; which must be
4112  // complete by instantiation time. Thus, do not search through the partial
4113  // specializations yet.
4114  // TODO: Unify with InstantiateClassTemplateSpecialization()?
4115  // Perhaps better after unification of DeduceTemplateArguments() and
4116  // getMoreSpecializedPartialSpecialization().
4117  bool InstantiationDependent = false;
4119  TemplateArgs, InstantiationDependent)) {
4120 
4122  Template->getPartialSpecializations(PartialSpecs);
4123 
4124  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4125  VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4126  TemplateDeductionInfo Info(FailedCandidates.getLocation());
4127 
4128  if (TemplateDeductionResult Result =
4129  DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4130  // Store the failed-deduction information for use in diagnostics, later.
4131  // TODO: Actually use the failed-deduction info?
4132  FailedCandidates.addCandidate().set(
4133  DeclAccessPair::make(Template, AS_public), Partial,
4134  MakeDeductionFailureInfo(Context, Result, Info));
4135  (void)Result;
4136  } else {
4137  Matched.push_back(PartialSpecMatchResult());
4138  Matched.back().Partial = Partial;
4139  Matched.back().Args = Info.take();
4140  }
4141  }
4142 
4143  if (Matched.size() >= 1) {
4144  SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4145  if (Matched.size() == 1) {
4146  // -- If exactly one matching specialization is found, the
4147  // instantiation is generated from that specialization.
4148  // We don't need to do anything for this.
4149  } else {
4150  // -- If more than one matching specialization is found, the
4151  // partial order rules (14.5.4.2) are used to determine
4152  // whether one of the specializations is more specialized
4153  // than the others. If none of the specializations is more
4154  // specialized than all of the other matching
4155  // specializations, then the use of the variable template is
4156  // ambiguous and the program is ill-formed.
4157  for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4158  PEnd = Matched.end();
4159  P != PEnd; ++P) {
4160  if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4161  PointOfInstantiation) ==
4162  P->Partial)
4163  Best = P;
4164  }
4165 
4166  // Determine if the best partial specialization is more specialized than
4167  // the others.
4168  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4169  PEnd = Matched.end();
4170  P != PEnd; ++P) {
4171  if (P != Best && getMoreSpecializedPartialSpecialization(
4172  P->Partial, Best->Partial,
4173  PointOfInstantiation) != Best->Partial) {
4174  AmbiguousPartialSpec = true;
4175  break;
4176  }
4177  }
4178  }
4179 
4180  // Instantiate using the best variable template partial specialization.
4181  InstantiationPattern = Best->Partial;
4182  InstantiationArgs = Best->Args;
4183  } else {
4184  // -- If no match is found, the instantiation is generated
4185  // from the primary template.
4186  // InstantiationPattern = Template->getTemplatedDecl();
4187  }
4188  }
4189 
4190  // 2. Create the canonical declaration.
4191  // Note that we do not instantiate a definition until we see an odr-use
4192  // in DoMarkVarDeclReferenced().
4193  // FIXME: LateAttrs et al.?
4194  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4195  Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4196  Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4197  if (!Decl)
4198  return true;
4199 
4200  if (AmbiguousPartialSpec) {
4201  // Partial ordering did not produce a clear winner. Complain.
4202  Decl->setInvalidDecl();
4203  Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4204  << Decl;
4205 
4206  // Print the matching partial specializations.
4207  for (MatchResult P : Matched)
4208  Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4209  << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4210  *P.Args);
4211  return true;
4212  }
4213 
4215  dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4216  Decl->setInstantiationOf(D, InstantiationArgs);
4217 
4218  checkSpecializationVisibility(TemplateNameLoc, Decl);
4219 
4220  assert(Decl && "No variable template specialization?");
4221  return Decl;
4222 }
4223 
4224 ExprResult
4226  const DeclarationNameInfo &NameInfo,
4227  VarTemplateDecl *Template, SourceLocation TemplateLoc,
4228  const TemplateArgumentListInfo *TemplateArgs) {
4229 
4230  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4231  *TemplateArgs);
4232  if (Decl.isInvalid())
4233  return ExprError();
4234 
4235  VarDecl *Var = cast<VarDecl>(Decl.get());
4236  if (!Var->getTemplateSpecializationKind())
4238  NameInfo.getLoc());
4239 
4240  // Build an ordinary singleton decl ref.
4241  return BuildDeclarationNameExpr(SS, NameInfo, Var,
4242  /*FoundD=*/nullptr, TemplateArgs);
4243 }
4244 
4246  SourceLocation Loc) {
4247  Diag(Loc, diag::err_template_missing_args)
4248  << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4249  if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4250  Diag(TD->getLocation(), diag::note_template_decl_here)
4251  << TD->getTemplateParameters()->getSourceRange();
4252  }
4253 }
4254 
4255 ExprResult
4257  const DeclarationNameInfo &NameInfo,
4258  ConceptDecl *Template,
4259  SourceLocation TemplateLoc,
4260  const TemplateArgumentListInfo *TemplateArgs) {
4261  // TODO: Do concept specialization here.
4262  Diag(NameInfo.getBeginLoc(), diag::err_concept_not_implemented) <<
4263  "concept specialization";
4264  return ExprError();
4265 }
4266 
4268  SourceLocation TemplateKWLoc,
4269  LookupResult &R,
4270  bool RequiresADL,
4271  const TemplateArgumentListInfo *TemplateArgs) {
4272  // FIXME: Can we do any checking at this point? I guess we could check the
4273  // template arguments that we have against the template name, if the template
4274  // name refers to a single template. That's not a terribly common case,
4275  // though.
4276  // foo<int> could identify a single function unambiguously
4277  // This approach does NOT work, since f<int>(1);
4278  // gets resolved prior to resorting to overload resolution
4279  // i.e., template<class T> void f(double);
4280  // vs template<class T, class U> void f(U);
4281 
4282  // These should be filtered out by our callers.
4283  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4284 
4285  // Non-function templates require a template argument list.
4286  if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4287  if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4288  diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4289  return ExprError();
4290  }
4291  }
4292 
4293  auto AnyDependentArguments = [&]() -> bool {
4294  bool InstantiationDependent;
4295  return TemplateArgs &&
4297  *TemplateArgs, InstantiationDependent);
4298  };
4299 
4300  // In C++1y, check variable template ids.
4301  if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4302  return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4304  TemplateKWLoc, TemplateArgs);
4305  }
4306 
4307  if (R.getAsSingle<ConceptDecl>() && !AnyDependentArguments()) {
4308  return CheckConceptTemplateId(SS, R.getLookupNameInfo(),
4309  R.getAsSingle<ConceptDecl>(),
4310  TemplateKWLoc, TemplateArgs);
4311  }
4312 
4313  // We don't want lookup warnings at this point.
4314  R.suppressDiagnostics();
4315 
4318  SS.getWithLocInContext(Context),
4319  TemplateKWLoc,
4320  R.getLookupNameInfo(),
4321  RequiresADL, TemplateArgs,
4322  R.begin(), R.end());
4323 
4324  return ULE;
4325 }
4326 
4327 // We actually only call this from template instantiation.
4328 ExprResult
4330  SourceLocation TemplateKWLoc,
4331  const DeclarationNameInfo &NameInfo,
4332  const TemplateArgumentListInfo *TemplateArgs) {
4333 
4334  assert(TemplateArgs || TemplateKWLoc.isValid());
4335  DeclContext *DC;
4336  if (!(DC = computeDeclContext(SS, false)) ||
4337  DC->isDependentContext() ||
4338  RequireCompleteDeclContext(SS, DC))
4339  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4340 
4341  bool MemberOfUnknownSpecialization;
4342  LookupResult R(*this, NameInfo, LookupOrdinaryName);
4343  if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4344  /*Entering*/false, MemberOfUnknownSpecialization,
4345  TemplateKWLoc))
4346  return ExprError();
4347 
4348  if (R.isAmbiguous())
4349  return ExprError();
4350 
4351  if (R.empty()) {
4352  Diag(NameInfo.getLoc(), diag::err_no_member)
4353  << NameInfo.getName() << DC << SS.getRange();
4354  return ExprError();
4355  }
4356 
4357  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4358  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4359  << SS.getScopeRep()
4360  << NameInfo.getName().getAsString() << SS.getRange();
4361  Diag(Temp->getLocation(), diag::note_referenced_class_template);
4362  return ExprError();
4363  }
4364 
4365  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4366 }
4367 
4368 /// Form a dependent template name.
4369 ///
4370 /// This action forms a dependent template name given the template
4371 /// name and its (presumably dependent) scope specifier. For
4372 /// example, given "MetaFun::template apply", the scope specifier \p
4373 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4374 /// of the "template" keyword, and "apply" is the \p Name.
4376  CXXScopeSpec &SS,
4377  SourceLocation TemplateKWLoc,
4378  const UnqualifiedId &Name,
4379  ParsedType ObjectType,
4380  bool EnteringContext,
4381  TemplateTy &Result,
4382  bool AllowInjectedClassName) {
4383  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4384  Diag(TemplateKWLoc,
4385  getLangOpts().CPlusPlus11 ?
4386  diag::warn_cxx98_compat_template_outside_of_template :
4387  diag::ext_template_outside_of_template)
4388  << FixItHint::CreateRemoval(TemplateKWLoc);
4389 
4390  DeclContext *LookupCtx = nullptr;
4391  if (SS.isSet())
4392  LookupCtx = computeDeclContext(SS, EnteringContext);
4393  if (!LookupCtx && ObjectType)
4394  LookupCtx = computeDeclContext(ObjectType.get());
4395  if (LookupCtx) {
4396  // C++0x [temp.names]p5:
4397  // If a name prefixed by the keyword template is not the name of
4398  // a template, the program is ill-formed. [Note: the keyword
4399  // template may not be applied to non-template members of class
4400  // templates. -end note ] [ Note: as is the case with the
4401  // typename prefix, the template prefix is allowed in cases
4402  // where it is not strictly necessary; i.e., when the
4403  // nested-name-specifier or the expression on the left of the ->
4404  // or . is not dependent on a template-parameter, or the use
4405  // does not appear in the scope of a template. -end note]
4406  //
4407  // Note: C++03 was more strict here, because it banned the use of
4408  // the "template" keyword prior to a template-name that was not a
4409  // dependent name. C++ DR468 relaxed this requirement (the
4410  // "template" keyword is now permitted). We follow the C++0x
4411  // rules, even in C++03 mode with a warning, retroactively applying the DR.
4412  bool MemberOfUnknownSpecialization;
4413  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4414  ObjectType, EnteringContext, Result,
4415  MemberOfUnknownSpecialization);
4416  if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4417  // This is a dependent template. Handle it below.
4418  } else if (TNK == TNK_Non_template) {
4419  // Do the lookup again to determine if this is a "nothing found" case or
4420  // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4421  // need to do this.
4422  DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4423  LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4424  LookupOrdinaryName);
4425  bool MOUS;
4426  if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4427  MOUS, TemplateKWLoc) && !R.isAmbiguous())
4428  Diag(Name.getBeginLoc(), diag::err_no_member)
4429  << DNI.getName() << LookupCtx << SS.getRange();
4430  return TNK_Non_template;
4431  } else {
4432  // We found something; return it.
4433  auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4434  if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4436  Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4437  // C++14 [class.qual]p2:
4438  // In a lookup in which function names are not ignored and the
4439  // nested-name-specifier nominates a class C, if the name specified
4440  // [...] is the injected-class-name of C, [...] the name is instead
4441  // considered to name the constructor
4442  //
4443  // We don't get here if naming the constructor would be valid, so we
4444  // just reject immediately and recover by treating the
4445  // injected-class-name as naming the template.
4446  Diag(Name.getBeginLoc(),
4447  diag::ext_out_of_line_qualified_id_type_names_constructor)
4448  << Name.Identifier
4449  << 0 /*injected-class-name used as template name*/
4450  << 1 /*'template' keyword was used*/;
4451  }
4452  return TNK;
4453  }
4454  }
4455 
4456  NestedNameSpecifier *Qualifier = SS.getScopeRep();
4457 
4458  switch (Name.getKind()) {
4460  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4461  Name.Identifier));
4463 
4465  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4467  return TNK_Function_template;
4468 
4470  llvm_unreachable("literal operator id cannot have a dependent scope");
4471 
4472  default:
4473  break;
4474  }
4475 
4476  Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4477  << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4478  << TemplateKWLoc;
4479  return TNK_Non_template;
4480 }
4481 
4483  TemplateArgumentLoc &AL,
4484  SmallVectorImpl<TemplateArgument> &Converted) {
4485  const TemplateArgument &Arg = AL.getArgument();
4486  QualType ArgType;
4487  TypeSourceInfo *TSI = nullptr;
4488 
4489  // Check template type parameter.
4490  switch(Arg.getKind()) {
4492  // C++ [temp.arg.type]p1:
4493  // A template-argument for a template-parameter which is a
4494  // type shall be a type-id.
4495  ArgType = Arg.getAsType();
4496  TSI = AL.getTypeSourceInfo();
4497  break;
4500  // We have a template type parameter but the template argument
4501  // is a template without any arguments.
4502  SourceRange SR = AL.getSourceRange();
4504  diagnoseMissingTemplateArguments(Name, SR.getEnd());
4505  return true;
4506  }
4508  // We have a template type parameter but the template argument is an
4509  // expression; see if maybe it is missing the "typename" keyword.
4510  CXXScopeSpec SS;
4511  DeclarationNameInfo NameInfo;
4512 
4513  if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4514  SS.Adopt(ArgExpr->getQualifierLoc());
4515  NameInfo = ArgExpr->getNameInfo();
4516  } else if (DependentScopeDeclRefExpr *ArgExpr =
4517  dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4518  SS.Adopt(ArgExpr->getQualifierLoc());
4519  NameInfo = ArgExpr->getNameInfo();
4520  } else if (CXXDependentScopeMemberExpr *ArgExpr =
4521  dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4522  if (ArgExpr->isImplicitAccess()) {
4523  SS.Adopt(ArgExpr->getQualifierLoc());
4524  NameInfo = ArgExpr->getMemberNameInfo();
4525  }
4526  }
4527 
4528  if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4529  LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4530  LookupParsedName(Result, CurScope, &SS);
4531 
4532  if (Result.getAsSingle<TypeDecl>() ||
4533  Result.getResultKind() ==
4535  // Suggest that the user add 'typename' before the NNS.
4536  SourceLocation Loc = AL.getSourceRange().getBegin();
4537  Diag(Loc, getLangOpts().MSVCCompat
4538  ? diag::ext_ms_template_type_arg_missing_typename
4539  : diag::err_template_arg_must_be_type_suggest)
4540  << FixItHint::CreateInsertion(Loc, "typename ");
4541  Diag(Param->getLocation(), diag::note_template_param_here);
4542 
4543  // Recover by synthesizing a type using the location information that we
4544  // already have.
4545  ArgType =
4546  Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4547  TypeLocBuilder TLB;
4548  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4549  TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4550  TL.setQualifierLoc(SS.getWithLocInContext(Context));
4551  TL.setNameLoc(NameInfo.getLoc());
4552  TSI = TLB.getTypeSourceInfo(Context, ArgType);
4553 
4554  // Overwrite our input TemplateArgumentLoc so that we can recover
4555  // properly.
4556  AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4558 
4559  break;
4560  }
4561  }
4562  // fallthrough
4563  LLVM_FALLTHROUGH;
4564  }
4565  default: {
4566  // We have a template type parameter but the template argument
4567  // is not a type.
4568  SourceRange SR = AL.getSourceRange();
4569  Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4570  Diag(Param->getLocation(), diag::note_template_param_here);
4571 
4572  return true;
4573  }
4574  }
4575 
4576  if (CheckTemplateArgument(Param, TSI))
4577  return true;
4578 
4579  // Add the converted template type argument.
4580  ArgType = Context.getCanonicalType(ArgType);
4581 
4582  // Objective-C ARC:
4583  // If an explicitly-specified template argument type is a lifetime type
4584  // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4585  if (getLangOpts().ObjCAutoRefCount &&
4586  ArgType->isObjCLifetimeType() &&
4587  !ArgType.getObjCLifetime()) {
4588  Qualifiers Qs;
4590  ArgType = Context.getQualifiedType(ArgType, Qs);
4591  }
4592 
4593  Converted.push_back(TemplateArgument(ArgType));
4594  return false;
4595 }
4596 
4597 /// Substitute template arguments into the default template argument for
4598 /// the given template type parameter.
4599 ///
4600 /// \param SemaRef the semantic analysis object for which we are performing
4601 /// the substitution.
4602 ///
4603 /// \param Template the template that we are synthesizing template arguments
4604 /// for.
4605 ///
4606 /// \param TemplateLoc the location of the template name that started the
4607 /// template-id we are checking.
4608 ///
4609 /// \param RAngleLoc the location of the right angle bracket ('>') that
4610 /// terminates the template-id.
4611 ///
4612 /// \param Param the template template parameter whose default we are
4613 /// substituting into.
4614 ///
4615 /// \param Converted the list of template arguments provided for template
4616 /// parameters that precede \p Param in the template parameter list.
4617 /// \returns the substituted template argument, or NULL if an error occurred.
4618 static TypeSourceInfo *
4620  TemplateDecl *Template,
4621  SourceLocation TemplateLoc,
4622  SourceLocation RAngleLoc,
4623  TemplateTypeParmDecl *Param,
4624  SmallVectorImpl<TemplateArgument> &Converted) {
4625  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4626 
4627  // If the argument type is dependent, instantiate it now based
4628  // on the previously-computed template arguments.
4629  if (ArgType->getType()->isInstantiationDependentType()) {
4630  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4631  Param, Template, Converted,
4632  SourceRange(TemplateLoc, RAngleLoc));
4633  if (Inst.isInvalid())
4634  return nullptr;
4635 
4636  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4637 
4638  // Only substitute for the innermost template argument list.
4639  MultiLevelTemplateArgumentList TemplateArgLists;
4640  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4641  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4642  TemplateArgLists.addOuterTemplateArguments(None);
4643 
4644  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4645  ArgType =
4646  SemaRef.SubstType(ArgType, TemplateArgLists,
4647  Param->getDefaultArgumentLoc(), Param->getDeclName());
4648  }
4649 
4650  return ArgType;
4651 }
4652 
4653 /// Substitute template arguments into the default template argument for
4654 /// the given non-type template parameter.
4655 ///
4656 /// \param SemaRef the semantic analysis object for which we are performing
4657 /// the substitution.
4658 ///
4659 /// \param Template the template that we are synthesizing template arguments
4660 /// for.
4661 ///
4662 /// \param TemplateLoc the location of the template name that started the
4663 /// template-id we are checking.
4664 ///
4665 /// \param RAngleLoc the location of the right angle bracket ('>') that
4666 /// terminates the template-id.
4667 ///
4668 /// \param Param the non-type template parameter whose default we are
4669 /// substituting into.
4670 ///
4671 /// \param Converted the list of template arguments provided for template
4672 /// parameters that precede \p Param in the template parameter list.
4673 ///
4674 /// \returns the substituted template argument, or NULL if an error occurred.
4675 static ExprResult
4677  TemplateDecl *Template,
4678  SourceLocation TemplateLoc,
4679  SourceLocation RAngleLoc,
4680  NonTypeTemplateParmDecl *Param,
4681  SmallVectorImpl<TemplateArgument> &Converted) {
4682  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4683  Param, Template, Converted,
4684  SourceRange(TemplateLoc, RAngleLoc));
4685  if (Inst.isInvalid())
4686  return ExprError();
4687 
4688  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4689 
4690  // Only substitute for the innermost template argument list.
4691  MultiLevelTemplateArgumentList TemplateArgLists;
4692  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4693  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4694  TemplateArgLists.addOuterTemplateArguments(None);
4695 
4696  EnterExpressionEvaluationContext ConstantEvaluated(
4698  return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4699 }
4700 
4701 /// Substitute template arguments into the default template argument for
4702 /// the given template template parameter.
4703 ///
4704 /// \param SemaRef the semantic analysis object for which we are performing
4705 /// the substitution.
4706 ///
4707 /// \param Template the template that we are synthesizing template arguments
4708 /// for.
4709 ///
4710 /// \param TemplateLoc the location of the template name that started the
4711 /// template-id we are checking.
4712 ///
4713 /// \param RAngleLoc the location of the right angle bracket ('>') that
4714 /// terminates the template-id.
4715 ///
4716 /// \param Param the template template parameter whose default we are
4717 /// substituting into.
4718 ///
4719 /// \param Converted the list of template arguments provided for template
4720 /// parameters that precede \p Param in the template parameter list.
4721 ///
4722 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4723 /// source-location information) that precedes the template name.
4724 ///
4725 /// \returns the substituted template argument, or NULL if an error occurred.
4726 static TemplateName
4728  TemplateDecl *Template,
4729  SourceLocation TemplateLoc,
4730  SourceLocation RAngleLoc,
4731  TemplateTemplateParmDecl *Param,
4733  NestedNameSpecifierLoc &QualifierLoc) {
4735  SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4736  SourceRange(TemplateLoc, RAngleLoc));
4737  if (Inst.isInvalid())
4738  return TemplateName();
4739 
4740  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4741 
4742  // Only substitute for the innermost template argument list.
4743  MultiLevelTemplateArgumentList TemplateArgLists;
4744  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4745  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4746  TemplateArgLists.addOuterTemplateArguments(None);
4747 
4748  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4749  // Substitute into the nested-name-specifier first,
4750  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4751  if (QualifierLoc) {
4752  QualifierLoc =
4753  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4754  if (!QualifierLoc)
4755  return TemplateName();
4756  }
4757 
4758  return SemaRef.SubstTemplateName(
4759  QualifierLoc,
4762  TemplateArgLists);
4763 }
4764 
4765 /// If the given template parameter has a default template
4766 /// argument, substitute into that default template argument and
4767 /// return the corresponding template argument.
4770  SourceLocation TemplateLoc,
4771  SourceLocation RAngleLoc,
4772  Decl *Param,
4774  &Converted,
4775  bool &HasDefaultArg) {
4776  HasDefaultArg = false;
4777 
4778  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4779  if (!hasVisibleDefaultArgument(TypeParm))
4780  return TemplateArgumentLoc();
4781 
4782  HasDefaultArg = true;
4783  TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4784  TemplateLoc,
4785  RAngleLoc,
4786  TypeParm,
4787  Converted);
4788  if (DI)
4789  return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4790 
4791  return TemplateArgumentLoc();
4792  }
4793 
4794  if (NonTypeTemplateParmDecl *NonTypeParm
4795  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4796  if (!hasVisibleDefaultArgument(NonTypeParm))
4797  return TemplateArgumentLoc();
4798 
4799  HasDefaultArg = true;
4800  ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4801  TemplateLoc,
4802  RAngleLoc,
4803  NonTypeParm,
4804  Converted);
4805  if (Arg.isInvalid())
4806  return TemplateArgumentLoc();
4807 
4808  Expr *ArgE = Arg.getAs<Expr>();
4809  return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4810  }
4811 
4812  TemplateTemplateParmDecl *TempTempParm
4813  = cast<TemplateTemplateParmDecl>(Param);
4814  if (!hasVisibleDefaultArgument(TempTempParm))
4815  return TemplateArgumentLoc();
4816 
4817  HasDefaultArg = true;
4818  NestedNameSpecifierLoc QualifierLoc;
4819  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4820  TemplateLoc,
4821  RAngleLoc,
4822  TempTempParm,
4823  Converted,
4824  QualifierLoc);
4825  if (TName.isNull())
4826  return TemplateArgumentLoc();
4827 
4828  return TemplateArgumentLoc(TemplateArgument(TName),
4829  TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4830  TempTempParm->getDefaultArgument().getTemplateNameLoc());
4831 }
4832 
4833 /// Convert a template-argument that we parsed as a type into a template, if
4834 /// possible. C++ permits injected-class-names to perform dual service as
4835 /// template template arguments and as template type arguments.
4837  // Extract and step over any surrounding nested-name-specifier.
4838  NestedNameSpecifierLoc QualLoc;
4839  if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4840  if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4841  return TemplateArgumentLoc();
4842 
4843  QualLoc = ETLoc.getQualifierLoc();
4844  TLoc = ETLoc.getNamedTypeLoc();
4845  }
4846 
4847  // If this type was written as an injected-class-name, it can be used as a
4848  // template template argument.
4849  if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4850  return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4851  QualLoc, InjLoc.getNameLoc());
4852 
4853  // If this type was written as an injected-class-name, it may have been
4854  // converted to a RecordType during instantiation. If the RecordType is
4855  // *not* wrapped in a TemplateSpecializationType and denotes a class
4856  // template specialization, it must have come from an injected-class-name.
4857  if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4858  if (auto *CTSD =
4859  dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4860  return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4861  QualLoc, RecLoc.getNameLoc());
4862 
4863  return TemplateArgumentLoc();
4864 }
4865 
4866 /// Check that the given template argument corresponds to the given
4867 /// template parameter.
4868 ///
4869 /// \param Param The template parameter against which the argument will be
4870 /// checked.
4871 ///
4872 /// \param Arg The template argument, which may be updated due to conversions.
4873 ///
4874 /// \param Template The template in which the template argument resides.
4875 ///
4876 /// \param TemplateLoc The location of the template name for the template
4877 /// whose argument list we're matching.
4878 ///
4879 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4880 /// the template argument list.
4881 ///
4882 /// \param ArgumentPackIndex The index into the argument pack where this
4883 /// argument will be placed. Only valid if the parameter is a parameter pack.
4884 ///
4885 /// \param Converted The checked, converted argument will be added to the
4886 /// end of this small vector.
4887 ///
4888 /// \param CTAK Describes how we arrived at this particular template argument:
4889 /// explicitly written, deduced, etc.
4890 ///
4891 /// \returns true on error, false otherwise.
4893  TemplateArgumentLoc &Arg,
4894  NamedDecl *Template,
4895  SourceLocation TemplateLoc,
4896  SourceLocation RAngleLoc,
4897  unsigned ArgumentPackIndex,
4900  // Check template type parameters.
4901  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4902  return CheckTemplateTypeArgument(TTP, Arg, Converted);
4903 
4904  // Check non-type template parameters.
4905  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4906  // Do substitution on the type of the non-type template parameter
4907  // with the template arguments we've seen thus far. But if the
4908  // template has a dependent context then we cannot substitute yet.
4909  QualType NTTPType = NTTP->getType();
4910  if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4911  NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4912 
4913  // FIXME: Do we need to substitute into parameters here if they're
4914  // instantiation-dependent but not dependent?
4915  if (NTTPType->isDependentType() &&
4916  !isa<TemplateTemplateParmDecl>(Template) &&
4917  !Template->getDeclContext()->isDependentContext()) {
4918  // Do substitution on the type of the non-type template parameter.
4919  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4920  NTTP, Converted,
4921  SourceRange(TemplateLoc, RAngleLoc));
4922  if (Inst.isInvalid())
4923  return true;
4924 
4926  Converted);
4927 
4928  // If the parameter is a pack expansion, expand this slice of the pack.
4929  if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
4930  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
4931  ArgumentPackIndex);
4932  NTTPType = SubstType(PET->getPattern(),
4933  MultiLevelTemplateArgumentList(TemplateArgs),
4934  NTTP->getLocation(),
4935  NTTP->getDeclName());
4936  } else {
4937  NTTPType = SubstType(NTTPType,
4938  MultiLevelTemplateArgumentList(TemplateArgs),
4939  NTTP->getLocation(),
4940  NTTP->getDeclName());
4941  }
4942 
4943  // If that worked, check the non-type template parameter type
4944  // for validity.
4945  if (!NTTPType.isNull())
4946  NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4947  NTTP->getLocation());
4948  if (NTTPType.isNull())
4949  return true;
4950  }
4951 
4952  switch (Arg.getArgument().getKind()) {
4954  llvm_unreachable("Should never see a NULL template argument here");
4955 
4957  TemplateArgument Result;
4958  unsigned CurSFINAEErrors = NumSFINAEErrors;
4959  ExprResult Res =
4960  CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4961  Result, CTAK);
4962  if (Res.isInvalid())
4963  return true;
4964  // If the current template argument causes an error, give up now.
4965  if (CurSFINAEErrors < NumSFINAEErrors)
4966  return true;
4967 
4968  // If the resulting expression is new, then use it in place of the
4969  // old expression in the template argument.
4970  if (Res.get() != Arg.getArgument().getAsExpr()) {
4971  TemplateArgument TA(Res.get());
4972  Arg = TemplateArgumentLoc(TA, Res.get());
4973  }
4974 
4975  Converted.push_back(Result);
4976  break;
4977  }
4978 
4982  // We've already checked this template argument, so just copy
4983  // it to the list of converted arguments.
4984  Converted.push_back(Arg.getArgument());
4985  break;
4986 
4989  // We were given a template template argument. It may not be ill-formed;
4990  // see below.
4991  if (DependentTemplateName *DTN
4994  // We have a template argument such as \c T::template X, which we
4995  // parsed as a template template argument. However, since we now
4996  // know that we need a non-type template argument, convert this
4997  // template name into an expression.
4998 
4999  DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5000  Arg.getTemplateNameLoc());
5001 
5002  CXXScopeSpec SS;
5003  SS.Adopt(Arg.getTemplateQualifierLoc());
5004  // FIXME: the template-template arg was a DependentTemplateName,
5005  // so it was provided with a template keyword. However, its source
5006  // location is not stored in the template argument structure.
5007  SourceLocation TemplateKWLoc;
5009  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5010  nullptr);
5011 
5012  // If we parsed the template argument as a pack expansion, create a
5013  // pack expansion expression.
5015  E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5016  if (E.isInvalid())
5017  return true;
5018  }
5019 
5020  TemplateArgument Result;
5021  E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5022  if (E.isInvalid())
5023  return true;
5024 
5025  Converted.push_back(Result);
5026  break;
5027  }
5028 
5029  // We have a template argument that actually does refer to a class
5030  // template, alias template, or template template parameter, and
5031  // therefore cannot be a non-type template argument.
5032  Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5033  << Arg.getSourceRange();
5034 
5035  Diag(Param->getLocation(), diag::note_template_param_here);
5036  return true;
5037 
5038  case TemplateArgument::Type: {
5039  // We have a non-type template parameter but the template
5040  // argument is a type.
5041 
5042  // C++ [temp.arg]p2:
5043  // In a template-argument, an ambiguity between a type-id and
5044  // an expression is resolved to a type-id, regardless of the
5045  // form of the corresponding template-parameter.
5046  //
5047  // We warn specifically about this case, since it can be rather
5048  // confusing for users.
5049  QualType T = Arg.getArgument().getAsType();
5050  SourceRange SR = Arg.getSourceRange();
5051  if (T->isFunctionType())
5052  Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5053  else
5054  Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5055  Diag(Param->getLocation(), diag::note_template_param_here);
5056  return true;
5057  }
5058 
5060  llvm_unreachable("Caller must expand template argument packs");
5061  }
5062 
5063  return false;
5064  }
5065 
5066 
5067  // Check template template parameters.
5068  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5069 
5070  TemplateParameterList *Params = TempParm->getTemplateParameters();
5071  if (TempParm->isExpandedParameterPack())
5072  Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5073 
5074  // Substitute into the template parameter list of the template
5075  // template parameter, since previously-supplied template arguments
5076  // may appear within the template template parameter.
5077  //
5078  // FIXME: Skip this if the parameters aren't instantiation-dependent.
5079  {
5080  // Set up a template instantiation context.
5082  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5083  TempParm, Converted,
5084  SourceRange(TemplateLoc, RAngleLoc));
5085  if (Inst.isInvalid())
5086  return true;
5087 
5088  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5089  Params = SubstTemplateParams(Params, CurContext,
5090  MultiLevelTemplateArgumentList(TemplateArgs));
5091  if (!Params)
5092  return true;
5093  }
5094 
5095  // C++1z [temp.local]p1: (DR1004)
5096  // When [the injected-class-name] is used [...] as a template-argument for
5097  // a template template-parameter [...] it refers to the class template
5098  // itself.
5099  if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5101  Arg.getTypeSourceInfo()->getTypeLoc());
5102  if (!ConvertedArg.getArgument().isNull())
5103  Arg = ConvertedArg;
5104  }
5105 
5106  switch (Arg.getArgument().getKind()) {
5108  llvm_unreachable("Should never see a NULL template argument here");
5109 
5112  if (CheckTemplateTemplateArgument(Params, Arg))
5113  return true;
5114 
5115  Converted.push_back(Arg.getArgument());
5116  break;
5117 
5120  // We have a template template parameter but the template
5121  // argument does not refer to a template.
5122  Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5123  << getLangOpts().CPlusPlus11;
5124  return true;
5125 
5127  llvm_unreachable("Declaration argument with template template parameter");
5129  llvm_unreachable("Integral argument with template template parameter");
5131  llvm_unreachable("Null pointer argument with template template parameter");
5132 
5134  llvm_unreachable("Caller must expand template argument packs");
5135  }
5136 
5137  return false;
5138 }
5139 
5140 /// Check whether the template parameter is a pack expansion, and if so,
5141 /// determine the number of parameters produced by that expansion. For instance:
5142 ///
5143 /// \code
5144 /// template<typename ...Ts> struct A {
5145 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5146 /// };
5147 /// \endcode
5148 ///
5149 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5150 /// is not a pack expansion, so returns an empty Optional.
5152  if (NonTypeTemplateParmDecl *NTTP
5153  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5154  if (NTTP->isExpandedParameterPack())
5155  return NTTP->getNumExpansionTypes();
5156  }
5157 
5158  if (TemplateTemplateParmDecl *TTP
5159  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5160  if (TTP->isExpandedParameterPack())
5161  return TTP->getNumExpansionTemplateParameters();
5162  }
5163 
5164  return None;
5165 }
5166 
5167 /// Diagnose a missing template argument.
5168 template<typename TemplateParmDecl>
5170  TemplateDecl *TD,
5171  const TemplateParmDecl *D,
5172  TemplateArgumentListInfo &Args) {
5173  // Dig out the most recent declaration of the template parameter; there may be
5174  // declarations of the template that are more recent than TD.
5175  D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5176  ->getTemplateParameters()
5177  ->getParam(D->getIndex()));
5178 
5179  // If there's a default argument that's not visible, diagnose that we're
5180  // missing a module import.
5182  if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5183  S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5184  D->getDefaultArgumentLoc(), Modules,
5186  /*Recover*/true);
5187  return true;
5188  }
5189 
5190  // FIXME: If there's a more recent default argument that *is* visible,
5191  // diagnose that it was declared too late.
5192 
5194 
5195  S.Diag(Loc, diag::err_template_arg_list_different_arity)
5196  << /*not enough args*/0
5198  << TD;
5199  S.Diag(TD->getLocation(), diag::note_template_decl_here)
5200  << Params->getSourceRange();
5201  return true;
5202 }
5203 
5204 /// Check that the given template argument list is well-formed
5205 /// for specializing the given template.
5207  TemplateDecl *Template, SourceLocation TemplateLoc,
5208  TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5210  bool UpdateArgsWithConversions) {
5211  // Make a copy of the template arguments for processing. Only make the
5212  // changes at the end when successful in matching the arguments to the
5213  // template.
5214  TemplateArgumentListInfo NewArgs = TemplateArgs;
5215 
5216  // Make sure we get the template parameter list from the most
5217  // recentdeclaration, since that is the only one that has is guaranteed to
5218  // have all the default template argument information.
5219  TemplateParameterList *Params =
5220  cast<TemplateDecl>(Template->getMostRecentDecl())
5221  ->getTemplateParameters();
5222 
5223  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5224 
5225  // C++ [temp.arg]p1:
5226  // [...] The type and form of each template-argument specified in
5227  // a template-id shall match the type and form specified for the
5228  // corresponding parameter declared by the template in its
5229  // template-parameter-list.
5230  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5231  SmallVector<TemplateArgument, 2> ArgumentPack;
5232  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5233  LocalInstantiationScope InstScope(*this, true);
5234  for (TemplateParameterList::iterator Param = Params->begin(),
5235  ParamEnd = Params->end();
5236  Param != ParamEnd; /* increment in loop */) {
5237  // If we have an expanded parameter pack, make sure we don't have too
5238  // many arguments.
5239  if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5240  if (*Expansions == ArgumentPack.size()) {
5241  // We're done with this parameter pack. Pack up its arguments and add
5242  // them to the list.
5243  Converted.push_back(
5244  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5245  ArgumentPack.clear();
5246 
5247  // This argument is assigned to the next parameter.
5248  ++Param;
5249  continue;
5250  } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5251  // Not enough arguments for this parameter pack.
5252  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5253  << /*not enough args*/0
5254  << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5255  << Template;
5256  Diag(Template->getLocation(), diag::note_template_decl_here)
5257  << Params->getSourceRange();
5258  return true;
5259  }
5260  }
5261 
5262  if (ArgIdx < NumArgs) {
5263  // Check the template argument we were given.
5264  if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5265  TemplateLoc, RAngleLoc,
5266  ArgumentPack.size(), Converted))
5267  return true;
5268 
5269  bool PackExpansionIntoNonPack =
5270  NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5271  (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5272  if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
5273  // Core issue 1430: we have a pack expansion as an argument to an
5274  // alias template, and it's not part of a parameter pack. This
5275  // can't be canonicalized, so reject it now.
5276  Diag(NewArgs[ArgIdx].getLocation(),
5277  diag::err_alias_template_expansion_into_fixed_list)
5278  << NewArgs[ArgIdx].getSourceRange();
5279  Diag((*Param)->getLocation(), diag::note_template_param_here);
5280  return true;
5281  }
5282 
5283  // We're now done with this argument.
5284  ++ArgIdx;
5285 
5286  if ((*Param)->isTemplateParameterPack()) {
5287  // The template parameter was a template parameter pack, so take the
5288  // deduced argument and place it on the argument pack. Note that we
5289  // stay on the same template parameter so that we can deduce more
5290  // arguments.
5291  ArgumentPack.push_back(Converted.pop_back_val());
5292  } else {
5293  // Move to the next template parameter.
5294  ++Param;
5295  }
5296 
5297  // If we just saw a pack expansion into a non-pack, then directly convert
5298  // the remaining arguments, because we don't know what parameters they'll
5299  // match up with.
5300  if (PackExpansionIntoNonPack) {
5301  if (!ArgumentPack.empty()) {
5302  // If we were part way through filling in an expanded parameter pack,
5303  // fall back to just producing individual arguments.
5304  Converted.insert(Converted.end(),
5305  ArgumentPack.begin(), ArgumentPack.end());
5306  ArgumentPack.clear();
5307  }
5308 
5309  while (ArgIdx < NumArgs) {
5310  Converted.push_back(NewArgs[ArgIdx].getArgument());
5311  ++ArgIdx;
5312  }
5313 
5314  return false;
5315  }
5316 
5317  continue;
5318  }
5319 
5320  // If we're checking a partial template argument list, we're done.
5321  if (PartialTemplateArgs) {
5322  if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5323  Converted.push_back(
5324  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5325 
5326  return false;
5327  }
5328 
5329  // If we have a template parameter pack with no more corresponding
5330  // arguments, just break out now and we'll fill in the argument pack below.
5331  if ((*Param)->isTemplateParameterPack()) {
5332  assert(!getExpandedPackSize(*Param) &&
5333  "Should have dealt with this already");
5334 
5335  // A non-expanded parameter pack before the end of the parameter list
5336  // only occurs for an ill-formed template parameter list, unless we've
5337  // got a partial argument list for a function template, so just bail out.
5338  if (Param + 1 != ParamEnd)
5339  return true;
5340 
5341  Converted.push_back(
5342  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5343  ArgumentPack.clear();
5344 
5345  ++Param;
5346  continue;
5347  }
5348 
5349  // Check whether we have a default argument.
5350  TemplateArgumentLoc Arg;
5351 
5352  // Retrieve the default template argument from the template
5353  // parameter. For each kind of template parameter, we substitute the
5354  // template arguments provided thus far and any "outer" template arguments
5355  // (when the template parameter was part of a nested template) into
5356  // the default argument.
5357  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5358  if (!hasVisibleDefaultArgument(TTP))
5359  return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5360  NewArgs);
5361 
5363  Template,
5364  TemplateLoc,
5365  RAngleLoc,
5366  TTP,
5367  Converted);
5368  if (!ArgType)
5369  return true;
5370 
5371  Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5372  ArgType);
5373  } else if (NonTypeTemplateParmDecl *NTTP
5374  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5375  if (!hasVisibleDefaultArgument(NTTP))
5376  return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5377  NewArgs);
5378 
5379  ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5380  TemplateLoc,
5381  RAngleLoc,
5382  NTTP,
5383  Converted);
5384  if (E.isInvalid())
5385  return true;
5386 
5387  Expr *Ex = E.getAs<Expr>();
5388  Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5389  } else {
5390  TemplateTemplateParmDecl *TempParm
5391  = cast<TemplateTemplateParmDecl>(*Param);
5392 
5393  if (!hasVisibleDefaultArgument(TempParm))
5394  return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5395  NewArgs);
5396 
5397  NestedNameSpecifierLoc QualifierLoc;
5398  TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5399  TemplateLoc,
5400  RAngleLoc,
5401  TempParm,
5402  Converted,
5403  QualifierLoc);
5404  if (Name.isNull())
5405  return true;
5406 
5407  Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5408  TempParm->getDefaultArgument().getTemplateNameLoc());
5409  }
5410 
5411  // Introduce an instantiation record that describes where we are using
5412  // the default template argument. We're not actually instantiating a
5413  // template here, we just create this object to put a note into the
5414  // context stack.
5415  InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5416  SourceRange(TemplateLoc, RAngleLoc));
5417  if (Inst.isInvalid())
5418  return true;
5419 
5420  // Check the default template argument.
5421  if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5422  RAngleLoc, 0, Converted))
5423  return true;
5424 
5425  // Core issue 150 (assumed resolution): if this is a template template
5426  // parameter, keep track of the default template arguments from the
5427  // template definition.
5428  if (isTemplateTemplateParameter)
5429  NewArgs.addArgument(Arg);
5430 
5431  // Move to the next template parameter and argument.
5432  ++Param;
5433  ++ArgIdx;
5434  }
5435 
5436  // If we're performing a partial argument substitution, allow any trailing
5437  // pack expansions; they might be empty. This can happen even if
5438  // PartialTemplateArgs is false (the list of arguments is complete but
5439  // still dependent).
5440  if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5441  CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5442  while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5443  Converted.push_back(NewArgs[ArgIdx++].getArgument());
5444  }
5445 
5446  // If we have any leftover arguments, then there were too many arguments.
5447  // Complain and fail.
5448  if (ArgIdx < NumArgs) {
5449  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5450  << /*too many args*/1
5451  << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5452  << Template
5453  << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5454  Diag(Template->getLocation(), diag::note_template_decl_here)
5455  << Params->getSourceRange();
5456  return true;
5457  }
5458 
5459  // No problems found with the new argument list, propagate changes back
5460  // to caller.
5461  if (UpdateArgsWithConversions)
5462  TemplateArgs = std::move(NewArgs);
5463 
5464  return false;
5465 }
5466 
5467 namespace {
5468  class UnnamedLocalNoLinkageFinder
5469  : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5470  {
5471  Sema &S;
5472  SourceRange SR;
5473 
5475 
5476  public:
5477  UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5478 
5479  bool Visit(QualType T) {
5480  return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5481  }
5482 
5483 #define TYPE(Class, Parent) \
5484  bool Visit##Class##Type(const Class##Type *);
5485 #define ABSTRACT_TYPE(Class, Parent) \
5486  bool Visit##Class##Type(const Class##Type *) { return false; }
5487 #define NON_CANONICAL_TYPE(Class, Parent) \
5488  bool Visit##Class##Type(const Class##Type *) { return false; }
5489 #include "clang/AST/TypeNodes.def"
5490 
5491  bool VisitTagDecl(const TagDecl *Tag);
5492  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5493  };
5494 } // end anonymous namespace
5495 
5496 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5497  return false;
5498 }
5499 
5500 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5501  return Visit(T->getElementType());
5502 }
5503 
5504 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5505  return Visit(T->getPointeeType());
5506 }
5507 
5508 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5509  const BlockPointerType* T) {
5510  return Visit(T->getPointeeType());
5511 }
5512 
5513 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5514  const LValueReferenceType* T) {
5515  return Visit(T->getPointeeType());
5516 }
5517 
5518 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5519  const RValueReferenceType* T) {
5520  return Visit(T->getPointeeType());
5521 }
5522 
5523 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5524  const MemberPointerType* T) {
5525  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5526 }
5527 
5528 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5529  const ConstantArrayType* T) {
5530  return Visit(T->getElementType());
5531 }
5532 
5533 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5534  const IncompleteArrayType* T) {
5535  return Visit(T->getElementType());
5536 }
5537 
5538 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5539  const VariableArrayType* T) {
5540  return Visit(T->getElementType());
5541 }
5542 
5543 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5544  const DependentSizedArrayType* T) {
5545  return Visit(T->getElementType());
5546 }
5547 
5548 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5549  const DependentSizedExtVectorType* T) {
5550  return Visit(T->getElementType());
5551 }
5552 
5553 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5554  const DependentAddressSpaceType *T) {
5555  return Visit(T->getPointeeType());
5556 }
5557 
5558 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5559  return Visit(T->getElementType());
5560 }
5561 
5562 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5563  const DependentVectorType *T) {
5564  return Visit(T->getElementType());
5565 }
5566 
5567 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5568  return Visit(T->getElementType());
5569 }
5570 
5571 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5572  const FunctionProtoType* T) {
5573  for (const auto &A : T->param_types()) {
5574  if (Visit(A))
5575  return true;
5576  }
5577 
5578  return Visit(T->getReturnType());
5579 }
5580 
5581 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5582  const FunctionNoProtoType* T) {
5583  return Visit(T->getReturnType());
5584 }
5585 
5586 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5587  const UnresolvedUsingType*) {
5588  return false;
5589 }
5590 
5591 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5592  return false;
5593 }
5594 
5595 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5596  return Visit(T->getUnderlyingType());
5597 }
5598 
5599 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5600  return false;
5601 }
5602 
5603 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5604  const UnaryTransformType*) {
5605  return false;
5606 }
5607 
5608 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5609  return Visit(T->getDeducedType());
5610 }
5611 
5612 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5614  return Visit(T->getDeducedType());
5615 }
5616 
5617 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5618  return VisitTagDecl(T->getDecl());
5619 }
5620 
5621 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5622  return VisitTagDecl(T->getDecl());
5623 }
5624 
5625 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5626  const TemplateTypeParmType*) {
5627  return false;
5628 }
5629 
5630 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5632  return false;
5633 }
5634 
5635 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5636  const TemplateSpecializationType*) {
5637  return false;
5638 }
5639 
5640 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5641  const InjectedClassNameType* T) {
5642  return VisitTagDecl(T->getDecl());
5643 }
5644 
5645 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5646  const DependentNameType* T) {
5647  return VisitNestedNameSpecifier(T->getQualifier());
5648 }
5649 
5650 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5652  return VisitNestedNameSpecifier(T->getQualifier());
5653 }
5654 
5655 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5656  const PackExpansionType* T) {
5657  return Visit(T->getPattern());
5658 }
5659 
5660 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5661  return false;
5662 }
5663 
5664 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5665  const ObjCInterfaceType *) {
5666  return false;
5667 }
5668 
5669 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5670  const ObjCObjectPointerType *) {
5671  return false;
5672 }
5673 
5674 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5675  return Visit(T->getValueType());
5676 }
5677 
5678 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5679  return false;
5680 }
5681 
5682 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5683  if (Tag->getDeclContext()->isFunctionOrMethod()) {
5684  S.Diag(SR.getBegin(),
5685  S.getLangOpts().CPlusPlus11 ?
5686  diag::warn_cxx98_compat_template_arg_local_type :
5687  diag::ext_template_arg_local_type)
5688  << S.Context.getTypeDeclType(Tag) << SR;
5689  return true;
5690  }
5691 
5692  if (!Tag->hasNameForLinkage()) {
5693  S.Diag(SR.getBegin(),
5694  S.getLangOpts().CPlusPlus11 ?
5695  diag::warn_cxx98_compat_template_arg_unnamed_type :
5696  diag::ext_template_arg_unnamed_type) << SR;
5697  S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5698  return true;
5699  }
5700 
5701  return false;
5702 }
5703 
5704 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5705  NestedNameSpecifier *NNS) {
5706  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5707  return true;
5708 
5709  switch (NNS->getKind()) {
5715  return false;
5716 
5719  return Visit(QualType(NNS->getAsType(), 0));
5720  }
5721  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5722 }
5723 
5724 /// Check a template argument against its corresponding
5725 /// template type parameter.
5726 ///
5727 /// This routine implements the semantics of C++ [temp.arg.type]. It
5728 /// returns true if an error occurred, and false otherwise.
5730  TypeSourceInfo *ArgInfo) {
5731  assert(ArgInfo && "invalid TypeSourceInfo");
5732  QualType Arg = ArgInfo->getType();
5733  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5734 
5735  if (Arg->isVariablyModifiedType()) {
5736  return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5737  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5738  return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5739  }
5740 
5741  // C++03 [temp.arg.type]p2:
5742  // A local type, a type with no linkage, an unnamed type or a type
5743  // compounded from any of these types shall not be used as a
5744  // template-argument for a template type-parameter.
5745  //
5746  // C++11 allows these, and even in C++03 we allow them as an extension with
5747  // a warning.
5748  if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5749  UnnamedLocalNoLinkageFinder Finder(*this, SR);
5750  (void)Finder.Visit(Context.getCanonicalType(Arg));
5751  }
5752 
5753  return false;
5754 }
5755 
5760 };
5761 
5762 /// Determine whether the given template argument is a null pointer
5763 /// value of the appropriate type.
5764 static NullPointerValueKind
5766  QualType ParamType, Expr *Arg,
5767  Decl *Entity = nullptr) {
5768  if (Arg->isValueDependent() || Arg->isTypeDependent())
5769  return NPV_NotNullPointer;
5770 
5771  // dllimport'd entities aren't constant but are available inside of template
5772  // arguments.
5773  if (Entity && Entity->hasAttr<DLLImportAttr>())
5774  return NPV_NotNullPointer;
5775 
5776  if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5777  llvm_unreachable(
5778  "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5779 
5780  if (!S.getLangOpts().CPlusPlus11)
5781  return NPV_NotNullPointer;
5782 
5783  // Determine whether we have a constant expression.
5785  if (ArgRV.isInvalid())
5786  ret