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