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