clang  3.8.0
SemaTemplate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===/
11 
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TypeVisitor.h"
21 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/Template.h"
32 #include "llvm/ADT/SmallBitVector.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 using namespace clang;
36 using namespace sema;
37 
38 // Exported for use by Parser.
41  unsigned N) {
42  if (!N) return SourceRange();
43  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
44 }
45 
46 /// \brief Determine whether the declaration found is acceptable as the name
47 /// of a template and, if so, return that template declaration. Otherwise,
48 /// returns NULL.
50  NamedDecl *Orig,
51  bool AllowFunctionTemplates) {
52  NamedDecl *D = Orig->getUnderlyingDecl();
53 
54  if (isa<TemplateDecl>(D)) {
55  if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
56  return nullptr;
57 
58  return Orig;
59  }
60 
61  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
62  // C++ [temp.local]p1:
63  // Like normal (non-template) classes, class templates have an
64  // injected-class-name (Clause 9). The injected-class-name
65  // can be used with or without a template-argument-list. When
66  // it is used without a template-argument-list, it is
67  // equivalent to the injected-class-name followed by the
68  // template-parameters of the class template enclosed in
69  // <>. When it is used with a template-argument-list, it
70  // refers to the specified class template specialization,
71  // which could be the current specialization or another
72  // specialization.
73  if (Record->isInjectedClassName()) {
74  Record = cast<CXXRecordDecl>(Record->getDeclContext());
75  if (Record->getDescribedClassTemplate())
76  return Record->getDescribedClassTemplate();
77 
79  = dyn_cast<ClassTemplateSpecializationDecl>(Record))
80  return Spec->getSpecializedTemplate();
81  }
82 
83  return nullptr;
84  }
85 
86  return nullptr;
87 }
88 
90  bool AllowFunctionTemplates) {
91  // The set of class templates we've already seen.
92  llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
93  LookupResult::Filter filter = R.makeFilter();
94  while (filter.hasNext()) {
95  NamedDecl *Orig = filter.next();
97  AllowFunctionTemplates);
98  if (!Repl)
99  filter.erase();
100  else if (Repl != Orig) {
101 
102  // C++ [temp.local]p3:
103  // A lookup that finds an injected-class-name (10.2) can result in an
104  // ambiguity in certain cases (for example, if it is found in more than
105  // one base class). If all of the injected-class-names that are found
106  // refer to specializations of the same class template, and if the name
107  // is used as a template-name, the reference refers to the class
108  // template itself and not a specialization thereof, and is not
109  // ambiguous.
110  if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
111  if (!ClassTemplates.insert(ClassTmpl).second) {
112  filter.erase();
113  continue;
114  }
115 
116  // FIXME: we promote access to public here as a workaround to
117  // the fact that LookupResult doesn't let us remember that we
118  // found this template through a particular injected class name,
119  // which means we end up doing nasty things to the invariants.
120  // Pretending that access is public is *much* safer.
121  filter.replace(Repl, AS_public);
122  }
123  }
124  filter.done();
125 }
126 
128  bool AllowFunctionTemplates) {
129  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
130  if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
131  return true;
132 
133  return false;
134 }
135 
137  CXXScopeSpec &SS,
138  bool hasTemplateKeyword,
140  ParsedType ObjectTypePtr,
141  bool EnteringContext,
142  TemplateTy &TemplateResult,
143  bool &MemberOfUnknownSpecialization) {
144  assert(getLangOpts().CPlusPlus && "No template names in C!");
145 
146  DeclarationName TName;
147  MemberOfUnknownSpecialization = false;
148 
149  switch (Name.getKind()) {
151  TName = DeclarationName(Name.Identifier);
152  break;
153 
157  break;
158 
161  break;
162 
163  default:
164  return TNK_Non_template;
165  }
166 
167  QualType ObjectType = ObjectTypePtr.get();
168 
169  LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
170  LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
171  MemberOfUnknownSpecialization);
172  if (R.empty()) return TNK_Non_template;
173  if (R.isAmbiguous()) {
174  // Suppress diagnostics; we'll redo this lookup later.
175  R.suppressDiagnostics();
176 
177  // FIXME: we might have ambiguous templates, in which case we
178  // should at least parse them properly!
179  return TNK_Non_template;
180  }
181 
182  TemplateName Template;
183  TemplateNameKind TemplateKind;
184 
185  unsigned ResultCount = R.end() - R.begin();
186  if (ResultCount > 1) {
187  // We assume that we'll preserve the qualifier from a function
188  // template name in other ways.
189  Template = Context.getOverloadedTemplateName(R.begin(), R.end());
190  TemplateKind = TNK_Function_template;
191 
192  // We'll do this lookup again later.
193  R.suppressDiagnostics();
194  } else {
195  TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
196 
197  if (SS.isSet() && !SS.isInvalid()) {
198  NestedNameSpecifier *Qualifier = SS.getScopeRep();
199  Template = Context.getQualifiedTemplateName(Qualifier,
200  hasTemplateKeyword, TD);
201  } else {
202  Template = TemplateName(TD);
203  }
204 
205  if (isa<FunctionTemplateDecl>(TD)) {
206  TemplateKind = TNK_Function_template;
207 
208  // We'll do this lookup again later.
209  R.suppressDiagnostics();
210  } else {
211  assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
212  isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
213  isa<BuiltinTemplateDecl>(TD));
214  TemplateKind =
215  isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
216  }
217  }
218 
219  TemplateResult = TemplateTy::make(Template);
220  return TemplateKind;
221 }
222 
224  SourceLocation IILoc,
225  Scope *S,
226  const CXXScopeSpec *SS,
227  TemplateTy &SuggestedTemplate,
228  TemplateNameKind &SuggestedKind) {
229  // We can't recover unless there's a dependent scope specifier preceding the
230  // template name.
231  // FIXME: Typo correction?
232  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
233  computeDeclContext(*SS))
234  return false;
235 
236  // The code is missing a 'template' keyword prior to the dependent template
237  // name.
239  Diag(IILoc, diag::err_template_kw_missing)
240  << Qualifier << II.getName()
241  << FixItHint::CreateInsertion(IILoc, "template ");
242  SuggestedTemplate
243  = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
244  SuggestedKind = TNK_Dependent_template_name;
245  return true;
246 }
247 
249  Scope *S, CXXScopeSpec &SS,
250  QualType ObjectType,
251  bool EnteringContext,
252  bool &MemberOfUnknownSpecialization) {
253  // Determine where to perform name lookup
254  MemberOfUnknownSpecialization = false;
255  DeclContext *LookupCtx = nullptr;
256  bool isDependent = false;
257  if (!ObjectType.isNull()) {
258  // This nested-name-specifier occurs in a member access expression, e.g.,
259  // x->B::f, and we are looking into the type of the object.
260  assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
261  LookupCtx = computeDeclContext(ObjectType);
262  isDependent = ObjectType->isDependentType();
263  assert((isDependent || !ObjectType->isIncompleteType() ||
264  ObjectType->castAs<TagType>()->isBeingDefined()) &&
265  "Caller should have completed object type");
266 
267  // Template names cannot appear inside an Objective-C class or object type.
268  if (ObjectType->isObjCObjectOrInterfaceType()) {
269  Found.clear();
270  return;
271  }
272  } else if (SS.isSet()) {
273  // This nested-name-specifier occurs after another nested-name-specifier,
274  // so long into the context associated with the prior nested-name-specifier.
275  LookupCtx = computeDeclContext(SS, EnteringContext);
276  isDependent = isDependentScopeSpecifier(SS);
277 
278  // The declaration context must be complete.
279  if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
280  return;
281  }
282 
283  bool ObjectTypeSearchedInScope = false;
284  bool AllowFunctionTemplatesInLookup = true;
285  if (LookupCtx) {
286  // Perform "qualified" name lookup into the declaration context we
287  // computed, which is either the type of the base of a member access
288  // expression or the declaration context associated with a prior
289  // nested-name-specifier.
290  LookupQualifiedName(Found, LookupCtx);
291  if (!ObjectType.isNull() && Found.empty()) {
292  // C++ [basic.lookup.classref]p1:
293  // In a class member access expression (5.2.5), if the . or -> token is
294  // immediately followed by an identifier followed by a <, the
295  // identifier must be looked up to determine whether the < is the
296  // beginning of a template argument list (14.2) or a less-than operator.
297  // The identifier is first looked up in the class of the object
298  // expression. If the identifier is not found, it is then looked up in
299  // the context of the entire postfix-expression and shall name a class
300  // or function template.
301  if (S) LookupName(Found, S);
302  ObjectTypeSearchedInScope = true;
303  AllowFunctionTemplatesInLookup = false;
304  }
305  } else if (isDependent && (!S || ObjectType.isNull())) {
306  // We cannot look into a dependent object type or nested nme
307  // specifier.
308  MemberOfUnknownSpecialization = true;
309  return;
310  } else {
311  // Perform unqualified name lookup in the current scope.
312  LookupName(Found, S);
313 
314  if (!ObjectType.isNull())
315  AllowFunctionTemplatesInLookup = false;
316  }
317 
318  if (Found.empty() && !isDependent) {
319  // If we did not find any names, attempt to correct any typos.
321  Found.clear();
322  // Simple filter callback that, for keywords, only accepts the C++ *_cast
323  auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
324  FilterCCC->WantTypeSpecifiers = false;
325  FilterCCC->WantExpressionKeywords = false;
326  FilterCCC->WantRemainingKeywords = false;
327  FilterCCC->WantCXXNamedCasts = true;
328  if (TypoCorrection Corrected = CorrectTypo(
329  Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
330  std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
331  Found.setLookupName(Corrected.getCorrection());
332  if (auto *ND = Corrected.getFoundDecl())
333  Found.addDecl(ND);
334  FilterAcceptableTemplateNames(Found);
335  if (!Found.empty()) {
336  if (LookupCtx) {
337  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
338  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
339  Name.getAsString() == CorrectedStr;
340  diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
341  << Name << LookupCtx << DroppedSpecifier
342  << SS.getRange());
343  } else {
344  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
345  }
346  }
347  } else {
348  Found.setLookupName(Name);
349  }
350  }
351 
352  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
353  if (Found.empty()) {
354  if (isDependent)
355  MemberOfUnknownSpecialization = true;
356  return;
357  }
358 
359  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
360  !getLangOpts().CPlusPlus11) {
361  // C++03 [basic.lookup.classref]p1:
362  // [...] If the lookup in the class of the object expression finds a
363  // template, the name is also looked up in the context of the entire
364  // postfix-expression and [...]
365  //
366  // Note: C++11 does not perform this second lookup.
367  LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
368  LookupOrdinaryName);
369  LookupName(FoundOuter, S);
370  FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
371 
372  if (FoundOuter.empty()) {
373  // - if the name is not found, the name found in the class of the
374  // object expression is used, otherwise
375  } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
376  FoundOuter.isAmbiguous()) {
377  // - if the name is found in the context of the entire
378  // postfix-expression and does not name a class template, the name
379  // found in the class of the object expression is used, otherwise
380  FoundOuter.clear();
381  } else if (!Found.isSuppressingDiagnostics()) {
382  // - if the name found is a class template, it must refer to the same
383  // entity as the one found in the class of the object expression,
384  // otherwise the program is ill-formed.
385  if (!Found.isSingleResult() ||
386  Found.getFoundDecl()->getCanonicalDecl()
387  != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
388  Diag(Found.getNameLoc(),
389  diag::ext_nested_name_member_ref_lookup_ambiguous)
390  << Found.getLookupName()
391  << ObjectType;
393  diag::note_ambig_member_ref_object_type)
394  << ObjectType;
395  Diag(FoundOuter.getFoundDecl()->getLocation(),
396  diag::note_ambig_member_ref_scope);
397 
398  // Recover by taking the template that we found in the object
399  // expression's type.
400  }
401  }
402  }
403 }
404 
405 /// ActOnDependentIdExpression - Handle a dependent id-expression that
406 /// was just parsed. This is only possible with an explicit scope
407 /// specifier naming a dependent type.
410  SourceLocation TemplateKWLoc,
411  const DeclarationNameInfo &NameInfo,
412  bool isAddressOfOperand,
413  const TemplateArgumentListInfo *TemplateArgs) {
414  DeclContext *DC = getFunctionLevelDeclContext();
415 
416  if (!isAddressOfOperand &&
417  isa<CXXMethodDecl>(DC) &&
418  cast<CXXMethodDecl>(DC)->isInstance()) {
419  QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
420 
421  // Since the 'this' expression is synthesized, we don't need to
422  // perform the double-lookup check.
423  NamedDecl *FirstQualifierInScope = nullptr;
424 
426  Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
427  /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
428  FirstQualifierInScope, NameInfo, TemplateArgs);
429  }
430 
431  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
432 }
433 
436  SourceLocation TemplateKWLoc,
437  const DeclarationNameInfo &NameInfo,
438  const TemplateArgumentListInfo *TemplateArgs) {
440  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
441  TemplateArgs);
442 }
443 
444 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
445 /// that the template parameter 'PrevDecl' is being shadowed by a new
446 /// declaration at location Loc. Returns true to indicate that this is
447 /// an error, and false otherwise.
449  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
450 
451  // Microsoft Visual C++ permits template parameters to be shadowed.
452  if (getLangOpts().MicrosoftExt)
453  return;
454 
455  // C++ [temp.local]p4:
456  // A template-parameter shall not be redeclared within its
457  // scope (including nested scopes).
458  Diag(Loc, diag::err_template_param_shadow)
459  << cast<NamedDecl>(PrevDecl)->getDeclName();
460  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
461  return;
462 }
463 
464 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
465 /// the parameter D to reference the templated declaration and return a pointer
466 /// to the template declaration. Otherwise, do nothing to D and return null.
468  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
469  D = Temp->getTemplatedDecl();
470  return Temp;
471  }
472  return nullptr;
473 }
474 
476  SourceLocation EllipsisLoc) const {
477  assert(Kind == Template &&
478  "Only template template arguments can be pack expansions here");
479  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
480  "Template template argument pack expansion without packs");
482  Result.EllipsisLoc = EllipsisLoc;
483  return Result;
484 }
485 
487  const ParsedTemplateArgument &Arg) {
488 
489  switch (Arg.getKind()) {
491  TypeSourceInfo *DI;
492  QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
493  if (!DI)
494  DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
495  return TemplateArgumentLoc(TemplateArgument(T), DI);
496  }
497 
499  Expr *E = static_cast<Expr *>(Arg.getAsExpr());
501  }
502 
504  TemplateName Template = Arg.getAsTemplate().get();
505  TemplateArgument TArg;
506  if (Arg.getEllipsisLoc().isValid())
507  TArg = TemplateArgument(Template, Optional<unsigned int>());
508  else
509  TArg = Template;
510  return TemplateArgumentLoc(TArg,
512  SemaRef.Context),
513  Arg.getLocation(),
514  Arg.getEllipsisLoc());
515  }
516  }
517 
518  llvm_unreachable("Unhandled parsed template argument");
519 }
520 
521 /// \brief Translates template arguments as provided by the parser
522 /// into template arguments used by semantic analysis.
524  TemplateArgumentListInfo &TemplateArgs) {
525  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
526  TemplateArgs.addArgument(translateTemplateArgument(*this,
527  TemplateArgsIn[I]));
528 }
529 
531  SourceLocation Loc,
532  IdentifierInfo *Name) {
533  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
535  if (PrevDecl && PrevDecl->isTemplateParameter())
536  SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
537 }
538 
539 /// ActOnTypeParameter - Called when a C++ template type parameter
540 /// (e.g., "typename T") has been parsed. Typename specifies whether
541 /// the keyword "typename" was used to declare the type parameter
542 /// (otherwise, "class" was used), and KeyLoc is the location of the
543 /// "class" or "typename" keyword. ParamName is the name of the
544 /// parameter (NULL indicates an unnamed template parameter) and
545 /// ParamNameLoc is the location of the parameter name (if any).
546 /// If the type parameter has a default argument, it will be added
547 /// later via ActOnTypeParameterDefault.
549  SourceLocation EllipsisLoc,
550  SourceLocation KeyLoc,
551  IdentifierInfo *ParamName,
552  SourceLocation ParamNameLoc,
553  unsigned Depth, unsigned Position,
554  SourceLocation EqualLoc,
555  ParsedType DefaultArg) {
556  assert(S->isTemplateParamScope() &&
557  "Template type parameter not in template parameter scope!");
558  bool Invalid = false;
559 
560  SourceLocation Loc = ParamNameLoc;
561  if (!ParamName)
562  Loc = KeyLoc;
563 
564  bool IsParameterPack = EllipsisLoc.isValid();
565  TemplateTypeParmDecl *Param
567  KeyLoc, Loc, Depth, Position, ParamName,
568  Typename, IsParameterPack);
569  Param->setAccess(AS_public);
570  if (Invalid)
571  Param->setInvalidDecl();
572 
573  if (ParamName) {
574  maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
575 
576  // Add the template parameter into the current scope.
577  S->AddDecl(Param);
578  IdResolver.AddDecl(Param);
579  }
580 
581  // C++0x [temp.param]p9:
582  // A default template-argument may be specified for any kind of
583  // template-parameter that is not a template parameter pack.
584  if (DefaultArg && IsParameterPack) {
585  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
586  DefaultArg = ParsedType();
587  }
588 
589  // Handle the default argument, if provided.
590  if (DefaultArg) {
591  TypeSourceInfo *DefaultTInfo;
592  GetTypeFromParser(DefaultArg, &DefaultTInfo);
593 
594  assert(DefaultTInfo && "expected source information for type");
595 
596  // Check for unexpanded parameter packs.
597  if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
598  UPPC_DefaultArgument))
599  return Param;
600 
601  // Check the template argument itself.
602  if (CheckTemplateArgument(Param, DefaultTInfo)) {
603  Param->setInvalidDecl();
604  return Param;
605  }
606 
607  Param->setDefaultArgument(DefaultTInfo);
608  }
609 
610  return Param;
611 }
612 
613 /// \brief Check that the type of a non-type template parameter is
614 /// well-formed.
615 ///
616 /// \returns the (possibly-promoted) parameter type if valid;
617 /// otherwise, produces a diagnostic and returns a NULL type.
618 QualType
620  // We don't allow variably-modified types as the type of non-type template
621  // parameters.
622  if (T->isVariablyModifiedType()) {
623  Diag(Loc, diag::err_variably_modified_nontype_template_param)
624  << T;
625  return QualType();
626  }
627 
628  // C++ [temp.param]p4:
629  //
630  // A non-type template-parameter shall have one of the following
631  // (optionally cv-qualified) types:
632  //
633  // -- integral or enumeration type,
634  if (T->isIntegralOrEnumerationType() ||
635  // -- pointer to object or pointer to function,
636  T->isPointerType() ||
637  // -- reference to object or reference to function,
638  T->isReferenceType() ||
639  // -- pointer to member,
640  T->isMemberPointerType() ||
641  // -- std::nullptr_t.
642  T->isNullPtrType() ||
643  // If T is a dependent type, we can't do the check now, so we
644  // assume that it is well-formed.
645  T->isDependentType()) {
646  // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
647  // are ignored when determining its type.
648  return T.getUnqualifiedType();
649  }
650 
651  // C++ [temp.param]p8:
652  //
653  // A non-type template-parameter of type "array of T" or
654  // "function returning T" is adjusted to be of type "pointer to
655  // T" or "pointer to function returning T", respectively.
656  else if (T->isArrayType() || T->isFunctionType())
657  return Context.getDecayedType(T);
658 
659  Diag(Loc, diag::err_template_nontype_parm_bad_type)
660  << T;
661 
662  return QualType();
663 }
664 
666  unsigned Depth,
667  unsigned Position,
668  SourceLocation EqualLoc,
669  Expr *Default) {
670  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
671  QualType T = TInfo->getType();
672 
673  assert(S->isTemplateParamScope() &&
674  "Non-type template parameter not in template parameter scope!");
675  bool Invalid = false;
676 
677  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
678  if (T.isNull()) {
679  T = Context.IntTy; // Recover with an 'int' type.
680  Invalid = true;
681  }
682 
683  IdentifierInfo *ParamName = D.getIdentifier();
684  bool IsParameterPack = D.hasEllipsis();
687  D.getLocStart(),
688  D.getIdentifierLoc(),
689  Depth, Position, ParamName, T,
690  IsParameterPack, TInfo);
691  Param->setAccess(AS_public);
692 
693  if (Invalid)
694  Param->setInvalidDecl();
695 
696  if (ParamName) {
698  ParamName);
699 
700  // Add the template parameter into the current scope.
701  S->AddDecl(Param);
702  IdResolver.AddDecl(Param);
703  }
704 
705  // C++0x [temp.param]p9:
706  // A default template-argument may be specified for any kind of
707  // template-parameter that is not a template parameter pack.
708  if (Default && IsParameterPack) {
709  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
710  Default = nullptr;
711  }
712 
713  // Check the well-formedness of the default template argument, if provided.
714  if (Default) {
715  // Check for unexpanded parameter packs.
716  if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
717  return Param;
718 
719  TemplateArgument Converted;
720  ExprResult DefaultRes =
721  CheckTemplateArgument(Param, Param->getType(), Default, Converted);
722  if (DefaultRes.isInvalid()) {
723  Param->setInvalidDecl();
724  return Param;
725  }
726  Default = DefaultRes.get();
727 
728  Param->setDefaultArgument(Default);
729  }
730 
731  return Param;
732 }
733 
734 /// ActOnTemplateTemplateParameter - Called when a C++ template template
735 /// parameter (e.g. T in template <template <typename> class T> class array)
736 /// has been parsed. S is the current scope.
738  SourceLocation TmpLoc,
739  TemplateParameterList *Params,
740  SourceLocation EllipsisLoc,
742  SourceLocation NameLoc,
743  unsigned Depth,
744  unsigned Position,
745  SourceLocation EqualLoc,
746  ParsedTemplateArgument Default) {
747  assert(S->isTemplateParamScope() &&
748  "Template template parameter not in template parameter scope!");
749 
750  // Construct the parameter object.
751  bool IsParameterPack = EllipsisLoc.isValid();
752  TemplateTemplateParmDecl *Param =
754  NameLoc.isInvalid()? TmpLoc : NameLoc,
755  Depth, Position, IsParameterPack,
756  Name, Params);
757  Param->setAccess(AS_public);
758 
759  // If the template template parameter has a name, then link the identifier
760  // into the scope and lookup mechanisms.
761  if (Name) {
762  maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
763 
764  S->AddDecl(Param);
765  IdResolver.AddDecl(Param);
766  }
767 
768  if (Params->size() == 0) {
769  Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
770  << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
771  Param->setInvalidDecl();
772  }
773 
774  // C++0x [temp.param]p9:
775  // A default template-argument may be specified for any kind of
776  // template-parameter that is not a template parameter pack.
777  if (IsParameterPack && !Default.isInvalid()) {
778  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
779  Default = ParsedTemplateArgument();
780  }
781 
782  if (!Default.isInvalid()) {
783  // Check only that we have a template template argument. We don't want to
784  // try to check well-formedness now, because our template template parameter
785  // might have dependent types in its template parameters, which we wouldn't
786  // be able to match now.
787  //
788  // If none of the template template parameter's template arguments mention
789  // other template parameters, we could actually perform more checking here.
790  // However, it isn't worth doing.
791  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
792  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
793  Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
794  << DefaultArg.getSourceRange();
795  return Param;
796  }
797 
798  // Check for unexpanded parameter packs.
799  if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
800  DefaultArg.getArgument().getAsTemplate(),
801  UPPC_DefaultArgument))
802  return Param;
803 
804  Param->setDefaultArgument(Context, DefaultArg);
805  }
806 
807  return Param;
808 }
809 
810 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
811 /// contains the template parameters in Params/NumParams.
814  SourceLocation ExportLoc,
815  SourceLocation TemplateLoc,
816  SourceLocation LAngleLoc,
817  ArrayRef<Decl *> Params,
818  SourceLocation RAngleLoc) {
819  if (ExportLoc.isValid())
820  Diag(ExportLoc, diag::warn_template_export_unsupported);
821 
823  Context, TemplateLoc, LAngleLoc,
824  llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
825  RAngleLoc);
826 }
827 
828 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
829  if (SS.isSet())
831 }
832 
834 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
835  SourceLocation KWLoc, CXXScopeSpec &SS,
838  TemplateParameterList *TemplateParams,
839  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
840  SourceLocation FriendLoc,
841  unsigned NumOuterTemplateParamLists,
842  TemplateParameterList** OuterTemplateParamLists,
843  SkipBodyInfo *SkipBody) {
844  assert(TemplateParams && TemplateParams->size() > 0 &&
845  "No template parameters");
846  assert(TUK != TUK_Reference && "Can only declare or define class templates");
847  bool Invalid = false;
848 
849  // Check that we can declare a template here.
850  if (CheckTemplateDeclScope(S, TemplateParams))
851  return true;
852 
854  assert(Kind != TTK_Enum && "can't build template of enumerated type");
855 
856  // There is no such thing as an unnamed class template.
857  if (!Name) {
858  Diag(KWLoc, diag::err_template_unnamed_class);
859  return true;
860  }
861 
862  // Find any previous declaration with this name. For a friend with no
863  // scope explicitly specified, we only look for tag declarations (per
864  // C++11 [basic.lookup.elab]p2).
865  DeclContext *SemanticContext;
866  LookupResult Previous(*this, Name, NameLoc,
867  (SS.isEmpty() && TUK == TUK_Friend)
868  ? LookupTagName : LookupOrdinaryName,
869  ForRedeclaration);
870  if (SS.isNotEmpty() && !SS.isInvalid()) {
871  SemanticContext = computeDeclContext(SS, true);
872  if (!SemanticContext) {
873  // FIXME: Horrible, horrible hack! We can't currently represent this
874  // in the AST, and historically we have just ignored such friend
875  // class templates, so don't complain here.
876  Diag(NameLoc, TUK == TUK_Friend
877  ? diag::warn_template_qualified_friend_ignored
878  : diag::err_template_qualified_declarator_no_match)
879  << SS.getScopeRep() << SS.getRange();
880  return TUK != TUK_Friend;
881  }
882 
883  if (RequireCompleteDeclContext(SS, SemanticContext))
884  return true;
885 
886  // If we're adding a template to a dependent context, we may need to
887  // rebuilding some of the types used within the template parameter list,
888  // now that we know what the current instantiation is.
889  if (SemanticContext->isDependentContext()) {
890  ContextRAII SavedContext(*this, SemanticContext);
891  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
892  Invalid = true;
893  } else if (TUK != TUK_Friend && TUK != TUK_Reference)
894  diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
895 
896  LookupQualifiedName(Previous, SemanticContext);
897  } else {
898  SemanticContext = CurContext;
899 
900  // C++14 [class.mem]p14:
901  // If T is the name of a class, then each of the following shall have a
902  // name different from T:
903  // -- every member template of class T
904  if (TUK != TUK_Friend &&
905  DiagnoseClassNameShadow(SemanticContext,
906  DeclarationNameInfo(Name, NameLoc)))
907  return true;
908 
909  LookupName(Previous, S);
910  }
911 
912  if (Previous.isAmbiguous())
913  return true;
914 
915  NamedDecl *PrevDecl = nullptr;
916  if (Previous.begin() != Previous.end())
917  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
918 
919  // If there is a previous declaration with the same name, check
920  // whether this is a valid redeclaration.
921  ClassTemplateDecl *PrevClassTemplate
922  = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
923 
924  // We may have found the injected-class-name of a class template,
925  // class template partial specialization, or class template specialization.
926  // In these cases, grab the template that is being defined or specialized.
927  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
928  cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
929  PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
930  PrevClassTemplate
931  = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
932  if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
933  PrevClassTemplate
934  = cast<ClassTemplateSpecializationDecl>(PrevDecl)
935  ->getSpecializedTemplate();
936  }
937  }
938 
939  if (TUK == TUK_Friend) {
940  // C++ [namespace.memdef]p3:
941  // [...] When looking for a prior declaration of a class or a function
942  // declared as a friend, and when the name of the friend class or
943  // function is neither a qualified name nor a template-id, scopes outside
944  // the innermost enclosing namespace scope are not considered.
945  if (!SS.isSet()) {
946  DeclContext *OutermostContext = CurContext;
947  while (!OutermostContext->isFileContext())
948  OutermostContext = OutermostContext->getLookupParent();
949 
950  if (PrevDecl &&
951  (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
952  OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
953  SemanticContext = PrevDecl->getDeclContext();
954  } else {
955  // Declarations in outer scopes don't matter. However, the outermost
956  // context we computed is the semantic context for our new
957  // declaration.
958  PrevDecl = PrevClassTemplate = nullptr;
959  SemanticContext = OutermostContext;
960 
961  // Check that the chosen semantic context doesn't already contain a
962  // declaration of this name as a non-tag type.
963  Previous.clear(LookupOrdinaryName);
964  DeclContext *LookupContext = SemanticContext;
965  while (LookupContext->isTransparentContext())
966  LookupContext = LookupContext->getLookupParent();
967  LookupQualifiedName(Previous, LookupContext);
968 
969  if (Previous.isAmbiguous())
970  return true;
971 
972  if (Previous.begin() != Previous.end())
973  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
974  }
975  }
976  } else if (PrevDecl &&
977  !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
978  S, SS.isValid()))
979  PrevDecl = PrevClassTemplate = nullptr;
980 
981  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
982  PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
983  if (SS.isEmpty() &&
984  !(PrevClassTemplate &&
985  PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
986  SemanticContext->getRedeclContext()))) {
987  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
988  Diag(Shadow->getTargetDecl()->getLocation(),
989  diag::note_using_decl_target);
990  Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
991  // Recover by ignoring the old declaration.
992  PrevDecl = PrevClassTemplate = nullptr;
993  }
994  }
995 
996  if (PrevClassTemplate) {
997  // Ensure that the template parameter lists are compatible. Skip this check
998  // for a friend in a dependent context: the template parameter list itself
999  // could be dependent.
1000  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1001  !TemplateParameterListsAreEqual(TemplateParams,
1002  PrevClassTemplate->getTemplateParameters(),
1003  /*Complain=*/true,
1004  TPL_TemplateMatch))
1005  return true;
1006 
1007  // C++ [temp.class]p4:
1008  // In a redeclaration, partial specialization, explicit
1009  // specialization or explicit instantiation of a class template,
1010  // the class-key shall agree in kind with the original class
1011  // template declaration (7.1.5.3).
1012  RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1013  if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1014  TUK == TUK_Definition, KWLoc, Name)) {
1015  Diag(KWLoc, diag::err_use_with_wrong_tag)
1016  << Name
1017  << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1018  Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1019  Kind = PrevRecordDecl->getTagKind();
1020  }
1021 
1022  // Check for redefinition of this class template.
1023  if (TUK == TUK_Definition) {
1024  if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1025  // If we have a prior definition that is not visible, treat this as
1026  // simply making that previous definition visible.
1027  NamedDecl *Hidden = nullptr;
1028  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1029  SkipBody->ShouldSkip = true;
1030  auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1031  assert(Tmpl && "original definition of a class template is not a "
1032  "class template?");
1033  makeMergedDefinitionVisible(Hidden, KWLoc);
1034  makeMergedDefinitionVisible(Tmpl, KWLoc);
1035  return Def;
1036  }
1037 
1038  Diag(NameLoc, diag::err_redefinition) << Name;
1039  Diag(Def->getLocation(), diag::note_previous_definition);
1040  // FIXME: Would it make sense to try to "forget" the previous
1041  // definition, as part of error recovery?
1042  return true;
1043  }
1044  }
1045  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1046  // Maybe we will complain about the shadowed template parameter.
1047  DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1048  // Just pretend that we didn't see the previous declaration.
1049  PrevDecl = nullptr;
1050  } else if (PrevDecl) {
1051  // C++ [temp]p5:
1052  // A class template shall not have the same name as any other
1053  // template, class, function, object, enumeration, enumerator,
1054  // namespace, or type in the same scope (3.3), except as specified
1055  // in (14.5.4).
1056  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1057  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1058  return true;
1059  }
1060 
1061  // Check the template parameter list of this declaration, possibly
1062  // merging in the template parameter list from the previous class
1063  // template declaration. Skip this check for a friend in a dependent
1064  // context, because the template parameter list might be dependent.
1065  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1066  CheckTemplateParameterList(
1067  TemplateParams,
1068  PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1069  : nullptr,
1070  (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1071  SemanticContext->isDependentContext())
1072  ? TPC_ClassTemplateMember
1073  : TUK == TUK_Friend ? TPC_FriendClassTemplate
1074  : TPC_ClassTemplate))
1075  Invalid = true;
1076 
1077  if (SS.isSet()) {
1078  // If the name of the template was qualified, we must be defining the
1079  // template out-of-line.
1080  if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1081  Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1082  : diag::err_member_decl_does_not_match)
1083  << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1084  Invalid = true;
1085  }
1086  }
1087 
1088  CXXRecordDecl *NewClass =
1089  CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1090  PrevClassTemplate?
1091  PrevClassTemplate->getTemplatedDecl() : nullptr,
1092  /*DelayTypeCreation=*/true);
1093  SetNestedNameSpecifier(NewClass, SS);
1094  if (NumOuterTemplateParamLists > 0)
1096  Context, llvm::makeArrayRef(OuterTemplateParamLists,
1097  NumOuterTemplateParamLists));
1098 
1099  // Add alignment attributes if necessary; these attributes are checked when
1100  // the ASTContext lays out the structure.
1101  if (TUK == TUK_Definition) {
1102  AddAlignmentAttributesForRecord(NewClass);
1103  AddMsStructLayoutForRecord(NewClass);
1104  }
1105 
1106  ClassTemplateDecl *NewTemplate
1107  = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1108  DeclarationName(Name), TemplateParams,
1109  NewClass, PrevClassTemplate);
1110  NewClass->setDescribedClassTemplate(NewTemplate);
1111 
1112  if (ModulePrivateLoc.isValid())
1113  NewTemplate->setModulePrivate();
1114 
1115  // Build the type for the class template declaration now.
1116  QualType T = NewTemplate->getInjectedClassNameSpecialization();
1117  T = Context.getInjectedClassNameType(NewClass, T);
1118  assert(T->isDependentType() && "Class template type is not dependent?");
1119  (void)T;
1120 
1121  // If we are providing an explicit specialization of a member that is a
1122  // class template, make a note of that.
1123  if (PrevClassTemplate &&
1124  PrevClassTemplate->getInstantiatedFromMemberTemplate())
1125  PrevClassTemplate->setMemberSpecialization();
1126 
1127  // Set the access specifier.
1128  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1129  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1130 
1131  // Set the lexical context of these templates
1132  NewClass->setLexicalDeclContext(CurContext);
1133  NewTemplate->setLexicalDeclContext(CurContext);
1134 
1135  if (TUK == TUK_Definition)
1136  NewClass->startDefinition();
1137 
1138  if (Attr)
1139  ProcessDeclAttributeList(S, NewClass, Attr);
1140 
1141  if (PrevClassTemplate)
1142  mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1143 
1144  AddPushedVisibilityAttribute(NewClass);
1145 
1146  if (TUK != TUK_Friend) {
1147  // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1148  Scope *Outer = S;
1149  while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1150  Outer = Outer->getParent();
1151  PushOnScopeChains(NewTemplate, Outer);
1152  } else {
1153  if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1154  NewTemplate->setAccess(PrevClassTemplate->getAccess());
1155  NewClass->setAccess(PrevClassTemplate->getAccess());
1156  }
1157 
1158  NewTemplate->setObjectOfFriendDecl();
1159 
1160  // Friend templates are visible in fairly strange ways.
1161  if (!CurContext->isDependentContext()) {
1162  DeclContext *DC = SemanticContext->getRedeclContext();
1163  DC->makeDeclVisibleInContext(NewTemplate);
1164  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1165  PushOnScopeChains(NewTemplate, EnclosingScope,
1166  /* AddToContext = */ false);
1167  }
1168 
1169  FriendDecl *Friend = FriendDecl::Create(
1170  Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1171  Friend->setAccess(AS_public);
1172  CurContext->addDecl(Friend);
1173  }
1174 
1175  if (Invalid) {
1176  NewTemplate->setInvalidDecl();
1177  NewClass->setInvalidDecl();
1178  }
1179 
1180  ActOnDocumentableDecl(NewTemplate);
1181 
1182  return NewTemplate;
1183 }
1184 
1185 /// \brief Diagnose the presence of a default template argument on a
1186 /// template parameter, which is ill-formed in certain contexts.
1187 ///
1188 /// \returns true if the default template argument should be dropped.
1191  SourceLocation ParamLoc,
1192  SourceRange DefArgRange) {
1193  switch (TPC) {
1195  case Sema::TPC_VarTemplate:
1197  return false;
1198 
1201  // C++ [temp.param]p9:
1202  // A default template-argument shall not be specified in a
1203  // function template declaration or a function template
1204  // definition [...]
1205  // If a friend function template declaration specifies a default
1206  // template-argument, that declaration shall be a definition and shall be
1207  // the only declaration of the function template in the translation unit.
1208  // (C++98/03 doesn't have this wording; see DR226).
1209  S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1210  diag::warn_cxx98_compat_template_parameter_default_in_function_template
1211  : diag::ext_template_parameter_default_in_function_template)
1212  << DefArgRange;
1213  return false;
1214 
1216  // C++0x [temp.param]p9:
1217  // A default template-argument shall not be specified in the
1218  // template-parameter-lists of the definition of a member of a
1219  // class template that appears outside of the member's class.
1220  S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1221  << DefArgRange;
1222  return true;
1223 
1226  // C++ [temp.param]p9:
1227  // A default template-argument shall not be specified in a
1228  // friend template declaration.
1229  S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1230  << DefArgRange;
1231  return true;
1232 
1233  // FIXME: C++0x [temp.param]p9 allows default template-arguments
1234  // for friend function templates if there is only a single
1235  // declaration (and it is a definition). Strange!
1236  }
1237 
1238  llvm_unreachable("Invalid TemplateParamListContext!");
1239 }
1240 
1241 /// \brief Check for unexpanded parameter packs within the template parameters
1242 /// of a template template parameter, recursively.
1244  TemplateTemplateParmDecl *TTP) {
1245  // A template template parameter which is a parameter pack is also a pack
1246  // expansion.
1247  if (TTP->isParameterPack())
1248  return false;
1249 
1251  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1252  NamedDecl *P = Params->getParam(I);
1253  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1254  if (!NTTP->isParameterPack() &&
1255  S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1256  NTTP->getTypeSourceInfo(),
1258  return true;
1259 
1260  continue;
1261  }
1262 
1263  if (TemplateTemplateParmDecl *InnerTTP
1264  = dyn_cast<TemplateTemplateParmDecl>(P))
1265  if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1266  return true;
1267  }
1268 
1269  return false;
1270 }
1271 
1272 /// \brief Checks the validity of a template parameter list, possibly
1273 /// considering the template parameter list from a previous
1274 /// declaration.
1275 ///
1276 /// If an "old" template parameter list is provided, it must be
1277 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1278 /// template parameter list.
1279 ///
1280 /// \param NewParams Template parameter list for a new template
1281 /// declaration. This template parameter list will be updated with any
1282 /// default arguments that are carried through from the previous
1283 /// template parameter list.
1284 ///
1285 /// \param OldParams If provided, template parameter list from a
1286 /// previous declaration of the same template. Default template
1287 /// arguments will be merged from the old template parameter list to
1288 /// the new template parameter list.
1289 ///
1290 /// \param TPC Describes the context in which we are checking the given
1291 /// template parameter list.
1292 ///
1293 /// \returns true if an error occurred, false otherwise.
1295  TemplateParameterList *OldParams,
1297  bool Invalid = false;
1298 
1299  // C++ [temp.param]p10:
1300  // The set of default template-arguments available for use with a
1301  // template declaration or definition is obtained by merging the
1302  // default arguments from the definition (if in scope) and all
1303  // declarations in scope in the same way default function
1304  // arguments are (8.3.6).
1305  bool SawDefaultArgument = false;
1306  SourceLocation PreviousDefaultArgLoc;
1307 
1308  // Dummy initialization to avoid warnings.
1309  TemplateParameterList::iterator OldParam = NewParams->end();
1310  if (OldParams)
1311  OldParam = OldParams->begin();
1312 
1313  bool RemoveDefaultArguments = false;
1314  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1315  NewParamEnd = NewParams->end();
1316  NewParam != NewParamEnd; ++NewParam) {
1317  // Variables used to diagnose redundant default arguments
1318  bool RedundantDefaultArg = false;
1319  SourceLocation OldDefaultLoc;
1320  SourceLocation NewDefaultLoc;
1321 
1322  // Variable used to diagnose missing default arguments
1323  bool MissingDefaultArg = false;
1324 
1325  // Variable used to diagnose non-final parameter packs
1326  bool SawParameterPack = false;
1327 
1328  if (TemplateTypeParmDecl *NewTypeParm
1329  = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1330  // Check the presence of a default argument here.
1331  if (NewTypeParm->hasDefaultArgument() &&
1333  NewTypeParm->getLocation(),
1334  NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1335  .getSourceRange()))
1336  NewTypeParm->removeDefaultArgument();
1337 
1338  // Merge default arguments for template type parameters.
1339  TemplateTypeParmDecl *OldTypeParm
1340  = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1341  if (NewTypeParm->isParameterPack()) {
1342  assert(!NewTypeParm->hasDefaultArgument() &&
1343  "Parameter packs can't have a default argument!");
1344  SawParameterPack = true;
1345  } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1346  NewTypeParm->hasDefaultArgument()) {
1347  OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1348  NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1349  SawDefaultArgument = true;
1350  RedundantDefaultArg = true;
1351  PreviousDefaultArgLoc = NewDefaultLoc;
1352  } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1353  // Merge the default argument from the old declaration to the
1354  // new declaration.
1355  NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1356  PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1357  } else if (NewTypeParm->hasDefaultArgument()) {
1358  SawDefaultArgument = true;
1359  PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1360  } else if (SawDefaultArgument)
1361  MissingDefaultArg = true;
1362  } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1363  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1364  // Check for unexpanded parameter packs.
1365  if (!NewNonTypeParm->isParameterPack() &&
1366  DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1367  NewNonTypeParm->getTypeSourceInfo(),
1368  UPPC_NonTypeTemplateParameterType)) {
1369  Invalid = true;
1370  continue;
1371  }
1372 
1373  // Check the presence of a default argument here.
1374  if (NewNonTypeParm->hasDefaultArgument() &&
1376  NewNonTypeParm->getLocation(),
1377  NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1378  NewNonTypeParm->removeDefaultArgument();
1379  }
1380 
1381  // Merge default arguments for non-type template parameters
1382  NonTypeTemplateParmDecl *OldNonTypeParm
1383  = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1384  if (NewNonTypeParm->isParameterPack()) {
1385  assert(!NewNonTypeParm->hasDefaultArgument() &&
1386  "Parameter packs can't have a default argument!");
1387  if (!NewNonTypeParm->isPackExpansion())
1388  SawParameterPack = true;
1389  } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1390  NewNonTypeParm->hasDefaultArgument()) {
1391  OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1392  NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1393  SawDefaultArgument = true;
1394  RedundantDefaultArg = true;
1395  PreviousDefaultArgLoc = NewDefaultLoc;
1396  } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1397  // Merge the default argument from the old declaration to the
1398  // new declaration.
1399  NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
1400  PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1401  } else if (NewNonTypeParm->hasDefaultArgument()) {
1402  SawDefaultArgument = true;
1403  PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1404  } else if (SawDefaultArgument)
1405  MissingDefaultArg = true;
1406  } else {
1407  TemplateTemplateParmDecl *NewTemplateParm
1408  = cast<TemplateTemplateParmDecl>(*NewParam);
1409 
1410  // Check for unexpanded parameter packs, recursively.
1411  if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1412  Invalid = true;
1413  continue;
1414  }
1415 
1416  // Check the presence of a default argument here.
1417  if (NewTemplateParm->hasDefaultArgument() &&
1419  NewTemplateParm->getLocation(),
1420  NewTemplateParm->getDefaultArgument().getSourceRange()))
1421  NewTemplateParm->removeDefaultArgument();
1422 
1423  // Merge default arguments for template template parameters
1424  TemplateTemplateParmDecl *OldTemplateParm
1425  = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1426  if (NewTemplateParm->isParameterPack()) {
1427  assert(!NewTemplateParm->hasDefaultArgument() &&
1428  "Parameter packs can't have a default argument!");
1429  if (!NewTemplateParm->isPackExpansion())
1430  SawParameterPack = true;
1431  } else if (OldTemplateParm &&
1432  hasVisibleDefaultArgument(OldTemplateParm) &&
1433  NewTemplateParm->hasDefaultArgument()) {
1434  OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1435  NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1436  SawDefaultArgument = true;
1437  RedundantDefaultArg = true;
1438  PreviousDefaultArgLoc = NewDefaultLoc;
1439  } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1440  // Merge the default argument from the old declaration to the
1441  // new declaration.
1442  NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
1443  PreviousDefaultArgLoc
1444  = OldTemplateParm->getDefaultArgument().getLocation();
1445  } else if (NewTemplateParm->hasDefaultArgument()) {
1446  SawDefaultArgument = true;
1447  PreviousDefaultArgLoc
1448  = NewTemplateParm->getDefaultArgument().getLocation();
1449  } else if (SawDefaultArgument)
1450  MissingDefaultArg = true;
1451  }
1452 
1453  // C++11 [temp.param]p11:
1454  // If a template parameter of a primary class template or alias template
1455  // is a template parameter pack, it shall be the last template parameter.
1456  if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1457  (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1458  TPC == TPC_TypeAliasTemplate)) {
1459  Diag((*NewParam)->getLocation(),
1460  diag::err_template_param_pack_must_be_last_template_parameter);
1461  Invalid = true;
1462  }
1463 
1464  if (RedundantDefaultArg) {
1465  // C++ [temp.param]p12:
1466  // A template-parameter shall not be given default arguments
1467  // by two different declarations in the same scope.
1468  Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1469  Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1470  Invalid = true;
1471  } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1472  // C++ [temp.param]p11:
1473  // If a template-parameter of a class template has a default
1474  // template-argument, each subsequent template-parameter shall either
1475  // have a default template-argument supplied or be a template parameter
1476  // pack.
1477  Diag((*NewParam)->getLocation(),
1478  diag::err_template_param_default_arg_missing);
1479  Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1480  Invalid = true;
1481  RemoveDefaultArguments = true;
1482  }
1483 
1484  // If we have an old template parameter list that we're merging
1485  // in, move on to the next parameter.
1486  if (OldParams)
1487  ++OldParam;
1488  }
1489 
1490  // We were missing some default arguments at the end of the list, so remove
1491  // all of the default arguments.
1492  if (RemoveDefaultArguments) {
1493  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1494  NewParamEnd = NewParams->end();
1495  NewParam != NewParamEnd; ++NewParam) {
1496  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1497  TTP->removeDefaultArgument();
1498  else if (NonTypeTemplateParmDecl *NTTP
1499  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1500  NTTP->removeDefaultArgument();
1501  else
1502  cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1503  }
1504  }
1505 
1506  return Invalid;
1507 }
1508 
1509 namespace {
1510 
1511 /// A class which looks for a use of a certain level of template
1512 /// parameter.
1513 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1515 
1516  unsigned Depth;
1517  bool Match;
1518  SourceLocation MatchLoc;
1519 
1520  DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1521 
1522  DependencyChecker(TemplateParameterList *Params) : Match(false) {
1523  NamedDecl *ND = Params->getParam(0);
1524  if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1525  Depth = PD->getDepth();
1526  } else if (NonTypeTemplateParmDecl *PD =
1527  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1528  Depth = PD->getDepth();
1529  } else {
1530  Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1531  }
1532  }
1533 
1534  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1535  if (ParmDepth >= Depth) {
1536  Match = true;
1537  MatchLoc = Loc;
1538  return true;
1539  }
1540  return false;
1541  }
1542 
1543  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1544  return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1545  }
1546 
1547  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1548  return !Matches(T->getDepth());
1549  }
1550 
1551  bool TraverseTemplateName(TemplateName N) {
1552  if (TemplateTemplateParmDecl *PD =
1553  dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1554  if (Matches(PD->getDepth()))
1555  return false;
1556  return super::TraverseTemplateName(N);
1557  }
1558 
1559  bool VisitDeclRefExpr(DeclRefExpr *E) {
1560  if (NonTypeTemplateParmDecl *PD =
1561  dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1562  if (Matches(PD->getDepth(), E->getExprLoc()))
1563  return false;
1564  return super::VisitDeclRefExpr(E);
1565  }
1566 
1567  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1568  return TraverseType(T->getReplacementType());
1569  }
1570 
1571  bool
1572  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1573  return TraverseTemplateArgument(T->getArgumentPack());
1574  }
1575 
1576  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1577  return TraverseType(T->getInjectedSpecializationType());
1578  }
1579 };
1580 }
1581 
1582 /// Determines whether a given type depends on the given parameter
1583 /// list.
1584 static bool
1586  DependencyChecker Checker(Params);
1587  Checker.TraverseType(T);
1588  return Checker.Match;
1589 }
1590 
1591 // Find the source range corresponding to the named type in the given
1592 // nested-name-specifier, if any.
1594  QualType T,
1595  const CXXScopeSpec &SS) {
1597  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1598  if (const Type *CurType = NNS->getAsType()) {
1599  if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1600  return NNSLoc.getTypeLoc().getSourceRange();
1601  } else
1602  break;
1603 
1604  NNSLoc = NNSLoc.getPrefix();
1605  }
1606 
1607  return SourceRange();
1608 }
1609 
1610 /// \brief Match the given template parameter lists to the given scope
1611 /// specifier, returning the template parameter list that applies to the
1612 /// name.
1613 ///
1614 /// \param DeclStartLoc the start of the declaration that has a scope
1615 /// specifier or a template parameter list.
1616 ///
1617 /// \param DeclLoc The location of the declaration itself.
1618 ///
1619 /// \param SS the scope specifier that will be matched to the given template
1620 /// parameter lists. This scope specifier precedes a qualified name that is
1621 /// being declared.
1622 ///
1623 /// \param TemplateId The template-id following the scope specifier, if there
1624 /// is one. Used to check for a missing 'template<>'.
1625 ///
1626 /// \param ParamLists the template parameter lists, from the outermost to the
1627 /// innermost template parameter lists.
1628 ///
1629 /// \param IsFriend Whether to apply the slightly different rules for
1630 /// matching template parameters to scope specifiers in friend
1631 /// declarations.
1632 ///
1633 /// \param IsExplicitSpecialization will be set true if the entity being
1634 /// declared is an explicit specialization, false otherwise.
1635 ///
1636 /// \returns the template parameter list, if any, that corresponds to the
1637 /// name that is preceded by the scope specifier @p SS. This template
1638 /// parameter list may have template parameters (if we're declaring a
1639 /// template) or may have no template parameters (if we're declaring a
1640 /// template specialization), or may be NULL (if what we're declaring isn't
1641 /// itself a template).
1643  SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1644  TemplateIdAnnotation *TemplateId,
1645  ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1646  bool &IsExplicitSpecialization, bool &Invalid) {
1647  IsExplicitSpecialization = false;
1648  Invalid = false;
1649 
1650  // The sequence of nested types to which we will match up the template
1651  // parameter lists. We first build this list by starting with the type named
1652  // by the nested-name-specifier and walking out until we run out of types.
1653  SmallVector<QualType, 4> NestedTypes;
1654  QualType T;
1655  if (SS.getScopeRep()) {
1656  if (CXXRecordDecl *Record
1657  = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1658  T = Context.getTypeDeclType(Record);
1659  else
1660  T = QualType(SS.getScopeRep()->getAsType(), 0);
1661  }
1662 
1663  // If we found an explicit specialization that prevents us from needing
1664  // 'template<>' headers, this will be set to the location of that
1665  // explicit specialization.
1666  SourceLocation ExplicitSpecLoc;
1667 
1668  while (!T.isNull()) {
1669  NestedTypes.push_back(T);
1670 
1671  // Retrieve the parent of a record type.
1672  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1673  // If this type is an explicit specialization, we're done.
1675  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1676  if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1677  Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1678  ExplicitSpecLoc = Spec->getLocation();
1679  break;
1680  }
1681  } else if (Record->getTemplateSpecializationKind()
1683  ExplicitSpecLoc = Record->getLocation();
1684  break;
1685  }
1686 
1687  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1688  T = Context.getTypeDeclType(Parent);
1689  else
1690  T = QualType();
1691  continue;
1692  }
1693 
1694  if (const TemplateSpecializationType *TST
1696  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1697  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1698  T = Context.getTypeDeclType(Parent);
1699  else
1700  T = QualType();
1701  continue;
1702  }
1703  }
1704 
1705  // Look one step prior in a dependent template specialization type.
1706  if (const DependentTemplateSpecializationType *DependentTST
1708  if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1709  T = QualType(NNS->getAsType(), 0);
1710  else
1711  T = QualType();
1712  continue;
1713  }
1714 
1715  // Look one step prior in a dependent name type.
1716  if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1717  if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1718  T = QualType(NNS->getAsType(), 0);
1719  else
1720  T = QualType();
1721  continue;
1722  }
1723 
1724  // Retrieve the parent of an enumeration type.
1725  if (const EnumType *EnumT = T->getAs<EnumType>()) {
1726  // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1727  // check here.
1728  EnumDecl *Enum = EnumT->getDecl();
1729 
1730  // Get to the parent type.
1731  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1732  T = Context.getTypeDeclType(Parent);
1733  else
1734  T = QualType();
1735  continue;
1736  }
1737 
1738  T = QualType();
1739  }
1740  // Reverse the nested types list, since we want to traverse from the outermost
1741  // to the innermost while checking template-parameter-lists.
1742  std::reverse(NestedTypes.begin(), NestedTypes.end());
1743 
1744  // C++0x [temp.expl.spec]p17:
1745  // A member or a member template may be nested within many
1746  // enclosing class templates. In an explicit specialization for
1747  // such a member, the member declaration shall be preceded by a
1748  // template<> for each enclosing class template that is
1749  // explicitly specialized.
1750  bool SawNonEmptyTemplateParameterList = false;
1751 
1752  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1753  if (SawNonEmptyTemplateParameterList) {
1754  Diag(DeclLoc, diag::err_specialize_member_of_template)
1755  << !Recovery << Range;
1756  Invalid = true;
1757  IsExplicitSpecialization = false;
1758  return true;
1759  }
1760 
1761  return false;
1762  };
1763 
1764  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1765  // Check that we can have an explicit specialization here.
1766  if (CheckExplicitSpecialization(Range, true))
1767  return true;
1768 
1769  // We don't have a template header, but we should.
1770  SourceLocation ExpectedTemplateLoc;
1771  if (!ParamLists.empty())
1772  ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1773  else
1774  ExpectedTemplateLoc = DeclStartLoc;
1775 
1776  Diag(DeclLoc, diag::err_template_spec_needs_header)
1777  << Range
1778  << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1779  return false;
1780  };
1781 
1782  unsigned ParamIdx = 0;
1783  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1784  ++TypeIdx) {
1785  T = NestedTypes[TypeIdx];
1786 
1787  // Whether we expect a 'template<>' header.
1788  bool NeedEmptyTemplateHeader = false;
1789 
1790  // Whether we expect a template header with parameters.
1791  bool NeedNonemptyTemplateHeader = false;
1792 
1793  // For a dependent type, the set of template parameters that we
1794  // expect to see.
1795  TemplateParameterList *ExpectedTemplateParams = nullptr;
1796 
1797  // C++0x [temp.expl.spec]p15:
1798  // A member or a member template may be nested within many enclosing
1799  // class templates. In an explicit specialization for such a member, the
1800  // member declaration shall be preceded by a template<> for each
1801  // enclosing class template that is explicitly specialized.
1802  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1804  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1805  ExpectedTemplateParams = Partial->getTemplateParameters();
1806  NeedNonemptyTemplateHeader = true;
1807  } else if (Record->isDependentType()) {
1808  if (Record->getDescribedClassTemplate()) {
1809  ExpectedTemplateParams = Record->getDescribedClassTemplate()
1810  ->getTemplateParameters();
1811  NeedNonemptyTemplateHeader = true;
1812  }
1813  } else if (ClassTemplateSpecializationDecl *Spec
1814  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1815  // C++0x [temp.expl.spec]p4:
1816  // Members of an explicitly specialized class template are defined
1817  // in the same manner as members of normal classes, and not using
1818  // the template<> syntax.
1819  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1820  NeedEmptyTemplateHeader = true;
1821  else
1822  continue;
1823  } else if (Record->getTemplateSpecializationKind()) {
1824  if (Record->getTemplateSpecializationKind()
1826  TypeIdx == NumTypes - 1)
1827  IsExplicitSpecialization = true;
1828 
1829  continue;
1830  }
1831  } else if (const TemplateSpecializationType *TST
1833  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1834  ExpectedTemplateParams = Template->getTemplateParameters();
1835  NeedNonemptyTemplateHeader = true;
1836  }
1837  } else if (T->getAs<DependentTemplateSpecializationType>()) {
1838  // FIXME: We actually could/should check the template arguments here
1839  // against the corresponding template parameter list.
1840  NeedNonemptyTemplateHeader = false;
1841  }
1842 
1843  // C++ [temp.expl.spec]p16:
1844  // In an explicit specialization declaration for a member of a class
1845  // template or a member template that ap- pears in namespace scope, the
1846  // member template and some of its enclosing class templates may remain
1847  // unspecialized, except that the declaration shall not explicitly
1848  // specialize a class member template if its en- closing class templates
1849  // are not explicitly specialized as well.
1850  if (ParamIdx < ParamLists.size()) {
1851  if (ParamLists[ParamIdx]->size() == 0) {
1852  if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1853  false))
1854  return nullptr;
1855  } else
1856  SawNonEmptyTemplateParameterList = true;
1857  }
1858 
1859  if (NeedEmptyTemplateHeader) {
1860  // If we're on the last of the types, and we need a 'template<>' header
1861  // here, then it's an explicit specialization.
1862  if (TypeIdx == NumTypes - 1)
1863  IsExplicitSpecialization = true;
1864 
1865  if (ParamIdx < ParamLists.size()) {
1866  if (ParamLists[ParamIdx]->size() > 0) {
1867  // The header has template parameters when it shouldn't. Complain.
1868  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1869  diag::err_template_param_list_matches_nontemplate)
1870  << T
1871  << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1872  ParamLists[ParamIdx]->getRAngleLoc())
1874  Invalid = true;
1875  return nullptr;
1876  }
1877 
1878  // Consume this template header.
1879  ++ParamIdx;
1880  continue;
1881  }
1882 
1883  if (!IsFriend)
1884  if (DiagnoseMissingExplicitSpecialization(
1886  return nullptr;
1887 
1888  continue;
1889  }
1890 
1891  if (NeedNonemptyTemplateHeader) {
1892  // In friend declarations we can have template-ids which don't
1893  // depend on the corresponding template parameter lists. But
1894  // assume that empty parameter lists are supposed to match this
1895  // template-id.
1896  if (IsFriend && T->isDependentType()) {
1897  if (ParamIdx < ParamLists.size() &&
1898  DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1899  ExpectedTemplateParams = nullptr;
1900  else
1901  continue;
1902  }
1903 
1904  if (ParamIdx < ParamLists.size()) {
1905  // Check the template parameter list, if we can.
1906  if (ExpectedTemplateParams &&
1907  !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1908  ExpectedTemplateParams,
1909  true, TPL_TemplateMatch))
1910  Invalid = true;
1911 
1912  if (!Invalid &&
1913  CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1914  TPC_ClassTemplateMember))
1915  Invalid = true;
1916 
1917  ++ParamIdx;
1918  continue;
1919  }
1920 
1921  Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1922  << T
1924  Invalid = true;
1925  continue;
1926  }
1927  }
1928 
1929  // If there were at least as many template-ids as there were template
1930  // parameter lists, then there are no template parameter lists remaining for
1931  // the declaration itself.
1932  if (ParamIdx >= ParamLists.size()) {
1933  if (TemplateId && !IsFriend) {
1934  // We don't have a template header for the declaration itself, but we
1935  // should.
1936  IsExplicitSpecialization = true;
1937  DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1938  TemplateId->RAngleLoc));
1939 
1940  // Fabricate an empty template parameter list for the invented header.
1942  SourceLocation(), None,
1943  SourceLocation());
1944  }
1945 
1946  return nullptr;
1947  }
1948 
1949  // If there were too many template parameter lists, complain about that now.
1950  if (ParamIdx < ParamLists.size() - 1) {
1951  bool HasAnyExplicitSpecHeader = false;
1952  bool AllExplicitSpecHeaders = true;
1953  for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1954  if (ParamLists[I]->size() == 0)
1955  HasAnyExplicitSpecHeader = true;
1956  else
1957  AllExplicitSpecHeaders = false;
1958  }
1959 
1960  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1961  AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1962  : diag::err_template_spec_extra_headers)
1963  << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1964  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1965 
1966  // If there was a specialization somewhere, such that 'template<>' is
1967  // not required, and there were any 'template<>' headers, note where the
1968  // specialization occurred.
1969  if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1970  Diag(ExplicitSpecLoc,
1971  diag::note_explicit_template_spec_does_not_need_header)
1972  << NestedTypes.back();
1973 
1974  // We have a template parameter list with no corresponding scope, which
1975  // means that the resulting template declaration can't be instantiated
1976  // properly (we'll end up with dependent nodes when we shouldn't).
1977  if (!AllExplicitSpecHeaders)
1978  Invalid = true;
1979  }
1980 
1981  // C++ [temp.expl.spec]p16:
1982  // In an explicit specialization declaration for a member of a class
1983  // template or a member template that ap- pears in namespace scope, the
1984  // member template and some of its enclosing class templates may remain
1985  // unspecialized, except that the declaration shall not explicitly
1986  // specialize a class member template if its en- closing class templates
1987  // are not explicitly specialized as well.
1988  if (ParamLists.back()->size() == 0 &&
1989  CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1990  false))
1991  return nullptr;
1992 
1993  // Return the last template parameter list, which corresponds to the
1994  // entity being declared.
1995  return ParamLists.back();
1996 }
1997 
1999  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2000  Diag(Template->getLocation(), diag::note_template_declared_here)
2001  << (isa<FunctionTemplateDecl>(Template)
2002  ? 0
2003  : isa<ClassTemplateDecl>(Template)
2004  ? 1
2005  : isa<VarTemplateDecl>(Template)
2006  ? 2
2007  : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2008  << Template->getDeclName();
2009  return;
2010  }
2011 
2013  for (OverloadedTemplateStorage::iterator I = OST->begin(),
2014  IEnd = OST->end();
2015  I != IEnd; ++I)
2016  Diag((*I)->getLocation(), diag::note_template_declared_here)
2017  << 0 << (*I)->getDeclName();
2018 
2019  return;
2020  }
2021 }
2022 
2023 static QualType
2025  const SmallVectorImpl<TemplateArgument> &Converted,
2026  SourceLocation TemplateLoc,
2027  TemplateArgumentListInfo &TemplateArgs) {
2028  ASTContext &Context = SemaRef.getASTContext();
2029  switch (BTD->getBuiltinTemplateKind()) {
2030  case BTK__make_integer_seq:
2031  // Specializations of __make_integer_seq<S, T, N> are treated like
2032  // S<T, 0, ..., N-1>.
2033 
2034  // C++14 [inteseq.intseq]p1:
2035  // T shall be an integer type.
2036  if (!Converted[1].getAsType()->isIntegralType(Context)) {
2037  SemaRef.Diag(TemplateArgs[1].getLocation(),
2038  diag::err_integer_sequence_integral_element_type);
2039  return QualType();
2040  }
2041 
2042  // C++14 [inteseq.make]p1:
2043  // If N is negative the program is ill-formed.
2044  TemplateArgument NumArgsArg = Converted[2];
2045  llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2046  if (NumArgs < 0) {
2047  SemaRef.Diag(TemplateArgs[2].getLocation(),
2048  diag::err_integer_sequence_negative_length);
2049  return QualType();
2050  }
2051 
2052  QualType ArgTy = NumArgsArg.getIntegralType();
2053  TemplateArgumentListInfo SyntheticTemplateArgs;
2054  // The type argument gets reused as the first template argument in the
2055  // synthetic template argument list.
2056  SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2057  // Expand N into 0 ... N-1.
2058  for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2059  I < NumArgs; ++I) {
2060  TemplateArgument TA(Context, I, ArgTy);
2062  TA, TemplateArgs[2].getLocation())
2063  .getAs<Expr>();
2064  SyntheticTemplateArgs.addArgument(
2066  }
2067  // The first template argument will be reused as the template decl that
2068  // our synthetic template arguments will be applied to.
2069  return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2070  TemplateLoc, SyntheticTemplateArgs);
2071  }
2072  llvm_unreachable("unexpected BuiltinTemplateDecl!");
2073 }
2074 
2076  SourceLocation TemplateLoc,
2077  TemplateArgumentListInfo &TemplateArgs) {
2080  if (DTN && DTN->isIdentifier())
2081  // When building a template-id where the template-name is dependent,
2082  // assume the template is a type template. Either our assumption is
2083  // correct, or the code is ill-formed and will be diagnosed when the
2084  // dependent name is substituted.
2086  DTN->getQualifier(),
2087  DTN->getIdentifier(),
2088  TemplateArgs);
2089 
2090  TemplateDecl *Template = Name.getAsTemplateDecl();
2091  if (!Template || isa<FunctionTemplateDecl>(Template) ||
2092  isa<VarTemplateDecl>(Template)) {
2093  // We might have a substituted template template parameter pack. If so,
2094  // build a template specialization type for it.
2096  return Context.getTemplateSpecializationType(Name, TemplateArgs);
2097 
2098  Diag(TemplateLoc, diag::err_template_id_not_a_type)
2099  << Name;
2100  NoteAllFoundTemplates(Name);
2101  return QualType();
2102  }
2103 
2104  // Check that the template argument list is well-formed for this
2105  // template.
2107  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2108  false, Converted))
2109  return QualType();
2110 
2111  QualType CanonType;
2112 
2113  bool InstantiationDependent = false;
2114  if (TypeAliasTemplateDecl *AliasTemplate =
2115  dyn_cast<TypeAliasTemplateDecl>(Template)) {
2116  // Find the canonical type for this type alias template specialization.
2117  TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2118  if (Pattern->isInvalidDecl())
2119  return QualType();
2120 
2122  Converted.data(), Converted.size());
2123 
2124  // Only substitute for the innermost template argument list.
2125  MultiLevelTemplateArgumentList TemplateArgLists;
2126  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2127  unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2128  for (unsigned I = 0; I < Depth; ++I)
2129  TemplateArgLists.addOuterTemplateArguments(None);
2130 
2132  InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2133  if (Inst.isInvalid())
2134  return QualType();
2135 
2136  CanonType = SubstType(Pattern->getUnderlyingType(),
2137  TemplateArgLists, AliasTemplate->getLocation(),
2138  AliasTemplate->getDeclName());
2139  if (CanonType.isNull())
2140  return QualType();
2141  } else if (Name.isDependent() ||
2143  TemplateArgs, InstantiationDependent)) {
2144  // This class template specialization is a dependent
2145  // type. Therefore, its canonical type is another class template
2146  // specialization type that contains all of the converted
2147  // arguments in canonical form. This ensures that, e.g., A<T> and
2148  // A<T, T> have identical types when A is declared as:
2149  //
2150  // template<typename T, typename U = T> struct A;
2151  TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2152  CanonType = Context.getTemplateSpecializationType(CanonName,
2153  Converted.data(),
2154  Converted.size());
2155 
2156  // FIXME: CanonType is not actually the canonical type, and unfortunately
2157  // it is a TemplateSpecializationType that we will never use again.
2158  // In the future, we need to teach getTemplateSpecializationType to only
2159  // build the canonical type and return that to us.
2160  CanonType = Context.getCanonicalType(CanonType);
2161 
2162  // This might work out to be a current instantiation, in which
2163  // case the canonical type needs to be the InjectedClassNameType.
2164  //
2165  // TODO: in theory this could be a simple hashtable lookup; most
2166  // changes to CurContext don't change the set of current
2167  // instantiations.
2168  if (isa<ClassTemplateDecl>(Template)) {
2169  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2170  // If we get out to a namespace, we're done.
2171  if (Ctx->isFileContext()) break;
2172 
2173  // If this isn't a record, keep looking.
2174  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2175  if (!Record) continue;
2176 
2177  // Look for one of the two cases with InjectedClassNameTypes
2178  // and check whether it's the same template.
2179  if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2180  !Record->getDescribedClassTemplate())
2181  continue;
2182 
2183  // Fetch the injected class name type and check whether its
2184  // injected type is equal to the type we just built.
2185  QualType ICNT = Context.getTypeDeclType(Record);
2186  QualType Injected = cast<InjectedClassNameType>(ICNT)
2187  ->getInjectedSpecializationType();
2188 
2189  if (CanonType != Injected->getCanonicalTypeInternal())
2190  continue;
2191 
2192  // If so, the canonical type of this TST is the injected
2193  // class name type of the record we just found.
2194  assert(ICNT.isCanonical());
2195  CanonType = ICNT;
2196  break;
2197  }
2198  }
2199  } else if (ClassTemplateDecl *ClassTemplate
2200  = dyn_cast<ClassTemplateDecl>(Template)) {
2201  // Find the class template specialization declaration that
2202  // corresponds to these arguments.
2203  void *InsertPos = nullptr;
2205  = ClassTemplate->findSpecialization(Converted, InsertPos);
2206  if (!Decl) {
2207  // This is the first time we have referenced this class template
2208  // specialization. Create the canonical declaration and add it to
2209  // the set of specializations.
2211  ClassTemplate->getTemplatedDecl()->getTagKind(),
2212  ClassTemplate->getDeclContext(),
2213  ClassTemplate->getTemplatedDecl()->getLocStart(),
2214  ClassTemplate->getLocation(),
2215  ClassTemplate,
2216  Converted.data(),
2217  Converted.size(), nullptr);
2218  ClassTemplate->AddSpecialization(Decl, InsertPos);
2219  if (ClassTemplate->isOutOfLine())
2220  Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2221  }
2222 
2223  // Diagnose uses of this specialization.
2224  (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2225 
2226  CanonType = Context.getTypeDeclType(Decl);
2227  assert(isa<RecordType>(CanonType) &&
2228  "type of non-dependent specialization is not a RecordType");
2229  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2230  CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2231  TemplateArgs);
2232  }
2233 
2234  // Build the fully-sugared type for this class template
2235  // specialization, which refers back to the class template
2236  // specialization we created or found.
2237  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2238 }
2239 
2240 TypeResult
2242  TemplateTy TemplateD, SourceLocation TemplateLoc,
2243  SourceLocation LAngleLoc,
2244  ASTTemplateArgsPtr TemplateArgsIn,
2245  SourceLocation RAngleLoc,
2246  bool IsCtorOrDtorName) {
2247  if (SS.isInvalid())
2248  return true;
2249 
2250  TemplateName Template = TemplateD.get();
2251 
2252  // Translate the parser's template argument list in our AST format.
2253  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2254  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2255 
2256  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2257  QualType T
2259  DTN->getQualifier(),
2260  DTN->getIdentifier(),
2261  TemplateArgs);
2262  // Build type-source information.
2263  TypeLocBuilder TLB;
2268  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2269  SpecTL.setTemplateNameLoc(TemplateLoc);
2270  SpecTL.setLAngleLoc(LAngleLoc);
2271  SpecTL.setRAngleLoc(RAngleLoc);
2272  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2273  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2274  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2275  }
2276 
2277  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2278 
2279  if (Result.isNull())
2280  return true;
2281 
2282  // Build type-source information.
2283  TypeLocBuilder TLB;
2285  = TLB.push<TemplateSpecializationTypeLoc>(Result);
2286  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2287  SpecTL.setTemplateNameLoc(TemplateLoc);
2288  SpecTL.setLAngleLoc(LAngleLoc);
2289  SpecTL.setRAngleLoc(RAngleLoc);
2290  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2291  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2292 
2293  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2294  // constructor or destructor name (in such a case, the scope specifier
2295  // will be attached to the enclosing Decl or Expr node).
2296  if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2297  // Create an elaborated-type-specifier containing the nested-name-specifier.
2298  Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2299  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2302  }
2303 
2304  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2305 }
2306 
2308  TypeSpecifierType TagSpec,
2309  SourceLocation TagLoc,
2310  CXXScopeSpec &SS,
2311  SourceLocation TemplateKWLoc,
2312  TemplateTy TemplateD,
2313  SourceLocation TemplateLoc,
2314  SourceLocation LAngleLoc,
2315  ASTTemplateArgsPtr TemplateArgsIn,
2316  SourceLocation RAngleLoc) {
2317  TemplateName Template = TemplateD.get();
2318 
2319  // Translate the parser's template argument list in our AST format.
2320  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2321  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2322 
2323  // Determine the tag kind
2325  ElaboratedTypeKeyword Keyword
2327 
2328  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2330  DTN->getQualifier(),
2331  DTN->getIdentifier(),
2332  TemplateArgs);
2333 
2334  // Build type-source information.
2335  TypeLocBuilder TLB;
2338  SpecTL.setElaboratedKeywordLoc(TagLoc);
2340  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2341  SpecTL.setTemplateNameLoc(TemplateLoc);
2342  SpecTL.setLAngleLoc(LAngleLoc);
2343  SpecTL.setRAngleLoc(RAngleLoc);
2344  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2345  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2346  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2347  }
2348 
2349  if (TypeAliasTemplateDecl *TAT =
2350  dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2351  // C++0x [dcl.type.elab]p2:
2352  // If the identifier resolves to a typedef-name or the simple-template-id
2353  // resolves to an alias template specialization, the
2354  // elaborated-type-specifier is ill-formed.
2355  Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2356  Diag(TAT->getLocation(), diag::note_declared_at);
2357  }
2358 
2359  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2360  if (Result.isNull())
2361  return TypeResult(true);
2362 
2363  // Check the tag kind
2364  if (const RecordType *RT = Result->getAs<RecordType>()) {
2365  RecordDecl *D = RT->getDecl();
2366 
2367  IdentifierInfo *Id = D->getIdentifier();
2368  assert(Id && "templated class must have an identifier");
2369 
2370  if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2371  TagLoc, Id)) {
2372  Diag(TagLoc, diag::err_use_with_wrong_tag)
2373  << Result
2375  Diag(D->getLocation(), diag::note_previous_use);
2376  }
2377  }
2378 
2379  // Provide source-location information for the template specialization.
2380  TypeLocBuilder TLB;
2382  = TLB.push<TemplateSpecializationTypeLoc>(Result);
2383  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2384  SpecTL.setTemplateNameLoc(TemplateLoc);
2385  SpecTL.setLAngleLoc(LAngleLoc);
2386  SpecTL.setRAngleLoc(RAngleLoc);
2387  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2388  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2389 
2390  // Construct an elaborated type containing the nested-name-specifier (if any)
2391  // and tag keyword.
2392  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2393  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2394  ElabTL.setElaboratedKeywordLoc(TagLoc);
2396  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2397 }
2398 
2400  Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2401  unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2402 
2403 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2404  NamedDecl *PrevDecl,
2405  SourceLocation Loc,
2406  bool IsPartialSpecialization);
2407 
2409 
2411  const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2412  switch (Arg.getKind()) {
2419  return false;
2420 
2421  case TemplateArgument::Type: {
2422  QualType Type = Arg.getAsType();
2423  const TemplateTypeParmType *TPT =
2425  return TPT && !Type.hasQualifiers() &&
2426  TPT->getDepth() == Depth && TPT->getIndex() == Index;
2427  }
2428 
2430  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2431  if (!DRE || !DRE->getDecl())
2432  return false;
2433  const NonTypeTemplateParmDecl *NTTP =
2434  dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2435  return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2436  }
2437 
2439  const TemplateTemplateParmDecl *TTP =
2440  dyn_cast_or_null<TemplateTemplateParmDecl>(
2442  return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2443  }
2444  llvm_unreachable("unexpected kind of template argument");
2445 }
2446 
2449  if (Params->size() != Args.size())
2450  return false;
2451 
2452  unsigned Depth = Params->getDepth();
2453 
2454  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2455  TemplateArgument Arg = Args[I];
2456 
2457  // If the parameter is a pack expansion, the argument must be a pack
2458  // whose only element is a pack expansion.
2459  if (Params->getParam(I)->isParameterPack()) {
2460  if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2461  !Arg.pack_begin()->isPackExpansion())
2462  return false;
2463  Arg = Arg.pack_begin()->getPackExpansionPattern();
2464  }
2465 
2466  if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2467  return false;
2468  }
2469 
2470  return true;
2471 }
2472 
2473 /// Convert the parser's template argument list representation into our form.
2476  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2477  TemplateId.RAngleLoc);
2478  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2479  TemplateId.NumArgs);
2480  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2481  return TemplateArgs;
2482 }
2483 
2485  Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2486  TemplateParameterList *TemplateParams, StorageClass SC,
2487  bool IsPartialSpecialization) {
2488  // D must be variable template id.
2489  assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2490  "Variable template specialization is declared with a template it.");
2491 
2492  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2493  TemplateArgumentListInfo TemplateArgs =
2494  makeTemplateArgumentListInfo(*this, *TemplateId);
2495  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2496  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2497  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2498 
2499  TemplateName Name = TemplateId->Template.get();
2500 
2501  // The template-id must name a variable template.
2502  VarTemplateDecl *VarTemplate =
2503  dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2504  if (!VarTemplate) {
2505  NamedDecl *FnTemplate;
2506  if (auto *OTS = Name.getAsOverloadedTemplate())
2507  FnTemplate = *OTS->begin();
2508  else
2509  FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2510  if (FnTemplate)
2511  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2512  << FnTemplate->getDeclName();
2513  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2514  << IsPartialSpecialization;
2515  }
2516 
2517  // Check for unexpanded parameter packs in any of the template arguments.
2518  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2519  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2520  UPPC_PartialSpecialization))
2521  return true;
2522 
2523  // Check that the template argument list is well-formed for this
2524  // template.
2526  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2527  false, Converted))
2528  return true;
2529 
2530  // Find the variable template (partial) specialization declaration that
2531  // corresponds to these arguments.
2532  if (IsPartialSpecialization) {
2534  *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2535  TemplateArgs.size(), Converted))
2536  return true;
2537 
2538  bool InstantiationDependent;
2539  if (!Name.isDependent() &&
2541  TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2542  InstantiationDependent)) {
2543  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2544  << VarTemplate->getDeclName();
2545  IsPartialSpecialization = false;
2546  }
2547 
2549  Converted)) {
2550  // C++ [temp.class.spec]p9b3:
2551  //
2552  // -- The argument list of the specialization shall not be identical
2553  // to the implicit argument list of the primary template.
2554  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2555  << /*variable template*/ 1
2556  << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2557  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2558  // FIXME: Recover from this by treating the declaration as a redeclaration
2559  // of the primary template.
2560  return true;
2561  }
2562  }
2563 
2564  void *InsertPos = nullptr;
2565  VarTemplateSpecializationDecl *PrevDecl = nullptr;
2566 
2567  if (IsPartialSpecialization)
2568  // FIXME: Template parameter list matters too
2569  PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2570  else
2571  PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2572 
2573  VarTemplateSpecializationDecl *Specialization = nullptr;
2574 
2575  // Check whether we can declare a variable template specialization in
2576  // the current scope.
2577  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2578  TemplateNameLoc,
2579  IsPartialSpecialization))
2580  return true;
2581 
2582  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2583  // Since the only prior variable template specialization with these
2584  // arguments was referenced but not declared, reuse that
2585  // declaration node as our own, updating its source location and
2586  // the list of outer template parameters to reflect our new declaration.
2587  Specialization = PrevDecl;
2588  Specialization->setLocation(TemplateNameLoc);
2589  PrevDecl = nullptr;
2590  } else if (IsPartialSpecialization) {
2591  // Create a new class template partial specialization declaration node.
2593  cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2596  Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2597  TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2598  Converted.data(), Converted.size(), TemplateArgs);
2599 
2600  if (!PrevPartial)
2601  VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2602  Specialization = Partial;
2603 
2604  // If we are providing an explicit specialization of a member variable
2605  // template specialization, make a note of that.
2606  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2607  PrevPartial->setMemberSpecialization();
2608 
2609  // Check that all of the template parameters of the variable template
2610  // partial specialization are deducible from the template
2611  // arguments. If not, this variable template partial specialization
2612  // will never be used.
2613  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2614  MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2615  TemplateParams->getDepth(), DeducibleParams);
2616 
2617  if (!DeducibleParams.all()) {
2618  unsigned NumNonDeducible =
2619  DeducibleParams.size() - DeducibleParams.count();
2620  Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2621  << /*variable template*/ 1 << (NumNonDeducible > 1)
2622  << SourceRange(TemplateNameLoc, RAngleLoc);
2623  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2624  if (!DeducibleParams[I]) {
2625  NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2626  if (Param->getDeclName())
2627  Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2628  << Param->getDeclName();
2629  else
2630  Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2631  << "(anonymous)";
2632  }
2633  }
2634  }
2635  } else {
2636  // Create a new class template specialization declaration node for
2637  // this explicit specialization or friend declaration.
2638  Specialization = VarTemplateSpecializationDecl::Create(
2639  Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2640  VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2641  Specialization->setTemplateArgsInfo(TemplateArgs);
2642 
2643  if (!PrevDecl)
2644  VarTemplate->AddSpecialization(Specialization, InsertPos);
2645  }
2646 
2647  // C++ [temp.expl.spec]p6:
2648  // If a template, a member template or the member of a class template is
2649  // explicitly specialized then that specialization shall be declared
2650  // before the first use of that specialization that would cause an implicit
2651  // instantiation to take place, in every translation unit in which such a
2652  // use occurs; no diagnostic is required.
2653  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2654  bool Okay = false;
2655  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2656  // Is there any previous explicit specialization declaration?
2658  Okay = true;
2659  break;
2660  }
2661  }
2662 
2663  if (!Okay) {
2664  SourceRange Range(TemplateNameLoc, RAngleLoc);
2665  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2666  << Name << Range;
2667 
2668  Diag(PrevDecl->getPointOfInstantiation(),
2669  diag::note_instantiation_required_here)
2670  << (PrevDecl->getTemplateSpecializationKind() !=
2672  return true;
2673  }
2674  }
2675 
2676  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2677  Specialization->setLexicalDeclContext(CurContext);
2678 
2679  // Add the specialization into its lexical context, so that it can
2680  // be seen when iterating through the list of declarations in that
2681  // context. However, specializations are not found by name lookup.
2682  CurContext->addDecl(Specialization);
2683 
2684  // Note that this is an explicit specialization.
2686 
2687  if (PrevDecl) {
2688  // Check that this isn't a redefinition of this specialization,
2689  // merging with previous declarations.
2690  LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2691  ForRedeclaration);
2692  PrevSpec.addDecl(PrevDecl);
2693  D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2694  } else if (Specialization->isStaticDataMember() &&
2695  Specialization->isOutOfLine()) {
2696  Specialization->setAccess(VarTemplate->getAccess());
2697  }
2698 
2699  // Link instantiations of static data members back to the template from
2700  // which they were instantiated.
2701  if (Specialization->isStaticDataMember())
2702  Specialization->setInstantiationOfStaticDataMember(
2703  VarTemplate->getTemplatedDecl(),
2704  Specialization->getSpecializationKind());
2705 
2706  return Specialization;
2707 }
2708 
2709 namespace {
2710 /// \brief A partial specialization whose template arguments have matched
2711 /// a given template-id.
2712 struct PartialSpecMatchResult {
2714  TemplateArgumentList *Args;
2715 };
2716 }
2717 
2718 DeclResult
2720  SourceLocation TemplateNameLoc,
2721  const TemplateArgumentListInfo &TemplateArgs) {
2722  assert(Template && "A variable template id without template?");
2723 
2724  // Check that the template argument list is well-formed for this template.
2726  if (CheckTemplateArgumentList(
2727  Template, TemplateNameLoc,
2728  const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2729  Converted))
2730  return true;
2731 
2732  // Find the variable template specialization declaration that
2733  // corresponds to these arguments.
2734  void *InsertPos = nullptr;
2735  if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2736  Converted, InsertPos))
2737  // If we already have a variable template specialization, return it.
2738  return Spec;
2739 
2740  // This is the first time we have referenced this variable template
2741  // specialization. Create the canonical declaration and add it to
2742  // the set of specializations, based on the closest partial specialization
2743  // that it represents. That is,
2744  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2746  Converted.data(), Converted.size());
2747  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2748  bool AmbiguousPartialSpec = false;
2749  typedef PartialSpecMatchResult MatchResult;
2751  SourceLocation PointOfInstantiation = TemplateNameLoc;
2752  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2753  /*ForTakingAddress=*/false);
2754 
2755  // 1. Attempt to find the closest partial specialization that this
2756  // specializes, if any.
2757  // If any of the template arguments is dependent, then this is probably
2758  // a placeholder for an incomplete declarative context; which must be
2759  // complete by instantiation time. Thus, do not search through the partial
2760  // specializations yet.
2761  // TODO: Unify with InstantiateClassTemplateSpecialization()?
2762  // Perhaps better after unification of DeduceTemplateArguments() and
2763  // getMoreSpecializedPartialSpecialization().
2764  bool InstantiationDependent = false;
2766  TemplateArgs, InstantiationDependent)) {
2767 
2769  Template->getPartialSpecializations(PartialSpecs);
2770 
2771  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2772  VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2773  TemplateDeductionInfo Info(FailedCandidates.getLocation());
2774 
2776  DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2777  // Store the failed-deduction information for use in diagnostics, later.
2778  // TODO: Actually use the failed-deduction info?
2779  FailedCandidates.addCandidate()
2780  .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2781  (void)Result;
2782  } else {
2783  Matched.push_back(PartialSpecMatchResult());
2784  Matched.back().Partial = Partial;
2785  Matched.back().Args = Info.take();
2786  }
2787  }
2788 
2789  if (Matched.size() >= 1) {
2790  SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2791  if (Matched.size() == 1) {
2792  // -- If exactly one matching specialization is found, the
2793  // instantiation is generated from that specialization.
2794  // We don't need to do anything for this.
2795  } else {
2796  // -- If more than one matching specialization is found, the
2797  // partial order rules (14.5.4.2) are used to determine
2798  // whether one of the specializations is more specialized
2799  // than the others. If none of the specializations is more
2800  // specialized than all of the other matching
2801  // specializations, then the use of the variable template is
2802  // ambiguous and the program is ill-formed.
2803  for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2804  PEnd = Matched.end();
2805  P != PEnd; ++P) {
2806  if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2807  PointOfInstantiation) ==
2808  P->Partial)
2809  Best = P;
2810  }
2811 
2812  // Determine if the best partial specialization is more specialized than
2813  // the others.
2814  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2815  PEnd = Matched.end();
2816  P != PEnd; ++P) {
2817  if (P != Best && getMoreSpecializedPartialSpecialization(
2818  P->Partial, Best->Partial,
2819  PointOfInstantiation) != Best->Partial) {
2820  AmbiguousPartialSpec = true;
2821  break;
2822  }
2823  }
2824  }
2825 
2826  // Instantiate using the best variable template partial specialization.
2827  InstantiationPattern = Best->Partial;
2828  InstantiationArgs = Best->Args;
2829  } else {
2830  // -- If no match is found, the instantiation is generated
2831  // from the primary template.
2832  // InstantiationPattern = Template->getTemplatedDecl();
2833  }
2834  }
2835 
2836  // 2. Create the canonical declaration.
2837  // Note that we do not instantiate the variable just yet, since
2838  // instantiation is handled in DoMarkVarDeclReferenced().
2839  // FIXME: LateAttrs et al.?
2840  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2841  Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2842  Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2843  if (!Decl)
2844  return true;
2845 
2846  if (AmbiguousPartialSpec) {
2847  // Partial ordering did not produce a clear winner. Complain.
2848  Decl->setInvalidDecl();
2849  Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2850  << Decl;
2851 
2852  // Print the matching partial specializations.
2853  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2854  PEnd = Matched.end();
2855  P != PEnd; ++P)
2856  Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2857  << getTemplateArgumentBindingsText(
2858  P->Partial->getTemplateParameters(), *P->Args);
2859  return true;
2860  }
2861 
2863  dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2864  Decl->setInstantiationOf(D, InstantiationArgs);
2865 
2866  assert(Decl && "No variable template specialization?");
2867  return Decl;
2868 }
2869 
2870 ExprResult
2872  const DeclarationNameInfo &NameInfo,
2873  VarTemplateDecl *Template, SourceLocation TemplateLoc,
2874  const TemplateArgumentListInfo *TemplateArgs) {
2875 
2876  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2877  *TemplateArgs);
2878  if (Decl.isInvalid())
2879  return ExprError();
2880 
2881  VarDecl *Var = cast<VarDecl>(Decl.get());
2882  if (!Var->getTemplateSpecializationKind())
2884  NameInfo.getLoc());
2885 
2886  // Build an ordinary singleton decl ref.
2887  return BuildDeclarationNameExpr(SS, NameInfo, Var,
2888  /*FoundD=*/nullptr, TemplateArgs);
2889 }
2890 
2892  SourceLocation TemplateKWLoc,
2893  LookupResult &R,
2894  bool RequiresADL,
2895  const TemplateArgumentListInfo *TemplateArgs) {
2896  // FIXME: Can we do any checking at this point? I guess we could check the
2897  // template arguments that we have against the template name, if the template
2898  // name refers to a single template. That's not a terribly common case,
2899  // though.
2900  // foo<int> could identify a single function unambiguously
2901  // This approach does NOT work, since f<int>(1);
2902  // gets resolved prior to resorting to overload resolution
2903  // i.e., template<class T> void f(double);
2904  // vs template<class T, class U> void f(U);
2905 
2906  // These should be filtered out by our callers.
2907  assert(!R.empty() && "empty lookup results when building templateid");
2908  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2909 
2910  // In C++1y, check variable template ids.
2911  bool InstantiationDependent;
2912  if (R.getAsSingle<VarTemplateDecl>() &&
2914  *TemplateArgs, InstantiationDependent)) {
2915  return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2917  TemplateKWLoc, TemplateArgs);
2918  }
2919 
2920  // We don't want lookup warnings at this point.
2921  R.suppressDiagnostics();
2922 
2926  TemplateKWLoc,
2927  R.getLookupNameInfo(),
2928  RequiresADL, TemplateArgs,
2929  R.begin(), R.end());
2930 
2931  return ULE;
2932 }
2933 
2934 // We actually only call this from template instantiation.
2935 ExprResult
2937  SourceLocation TemplateKWLoc,
2938  const DeclarationNameInfo &NameInfo,
2939  const TemplateArgumentListInfo *TemplateArgs) {
2940 
2941  assert(TemplateArgs || TemplateKWLoc.isValid());
2942  DeclContext *DC;
2943  if (!(DC = computeDeclContext(SS, false)) ||
2944  DC->isDependentContext() ||
2945  RequireCompleteDeclContext(SS, DC))
2946  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2947 
2948  bool MemberOfUnknownSpecialization;
2949  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2950  LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2951  MemberOfUnknownSpecialization);
2952 
2953  if (R.isAmbiguous())
2954  return ExprError();
2955 
2956  if (R.empty()) {
2957  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2958  << NameInfo.getName() << SS.getRange();
2959  return ExprError();
2960  }
2961 
2962  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2963  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2964  << SS.getScopeRep()
2965  << NameInfo.getName().getAsString() << SS.getRange();
2966  Diag(Temp->getLocation(), diag::note_referenced_class_template);
2967  return ExprError();
2968  }
2969 
2970  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2971 }
2972 
2973 /// \brief Form a dependent template name.
2974 ///
2975 /// This action forms a dependent template name given the template
2976 /// name and its (presumably dependent) scope specifier. For
2977 /// example, given "MetaFun::template apply", the scope specifier \p
2978 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2979 /// of the "template" keyword, and "apply" is the \p Name.
2981  CXXScopeSpec &SS,
2982  SourceLocation TemplateKWLoc,
2984  ParsedType ObjectType,
2985  bool EnteringContext,
2986  TemplateTy &Result) {
2987  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2988  Diag(TemplateKWLoc,
2989  getLangOpts().CPlusPlus11 ?
2990  diag::warn_cxx98_compat_template_outside_of_template :
2991  diag::ext_template_outside_of_template)
2992  << FixItHint::CreateRemoval(TemplateKWLoc);
2993 
2994  DeclContext *LookupCtx = nullptr;
2995  if (SS.isSet())
2996  LookupCtx = computeDeclContext(SS, EnteringContext);
2997  if (!LookupCtx && ObjectType)
2998  LookupCtx = computeDeclContext(ObjectType.get());
2999  if (LookupCtx) {
3000  // C++0x [temp.names]p5:
3001  // If a name prefixed by the keyword template is not the name of
3002  // a template, the program is ill-formed. [Note: the keyword
3003  // template may not be applied to non-template members of class
3004  // templates. -end note ] [ Note: as is the case with the
3005  // typename prefix, the template prefix is allowed in cases
3006  // where it is not strictly necessary; i.e., when the
3007  // nested-name-specifier or the expression on the left of the ->
3008  // or . is not dependent on a template-parameter, or the use
3009  // does not appear in the scope of a template. -end note]
3010  //
3011  // Note: C++03 was more strict here, because it banned the use of
3012  // the "template" keyword prior to a template-name that was not a
3013  // dependent name. C++ DR468 relaxed this requirement (the
3014  // "template" keyword is now permitted). We follow the C++0x
3015  // rules, even in C++03 mode with a warning, retroactively applying the DR.
3016  bool MemberOfUnknownSpecialization;
3017  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3018  ObjectType, EnteringContext, Result,
3019  MemberOfUnknownSpecialization);
3020  if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3021  isa<CXXRecordDecl>(LookupCtx) &&
3022  (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3023  cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3024  // This is a dependent template. Handle it below.
3025  } else if (TNK == TNK_Non_template) {
3026  Diag(Name.getLocStart(),
3027  diag::err_template_kw_refers_to_non_template)
3028  << GetNameFromUnqualifiedId(Name).getName()
3029  << Name.getSourceRange()
3030  << TemplateKWLoc;
3031  return TNK_Non_template;
3032  } else {
3033  // We found something; return it.
3034  return TNK;
3035  }
3036  }
3037 
3038  NestedNameSpecifier *Qualifier = SS.getScopeRep();
3039 
3040  switch (Name.getKind()) {
3042  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3043  Name.Identifier));
3045 
3047  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3049  return TNK_Function_template;
3050 
3052  llvm_unreachable("literal operator id cannot have a dependent scope");
3053 
3054  default:
3055  break;
3056  }
3057 
3058  Diag(Name.getLocStart(),
3059  diag::err_template_kw_refers_to_non_template)
3060  << GetNameFromUnqualifiedId(Name).getName()
3061  << Name.getSourceRange()
3062  << TemplateKWLoc;
3063  return TNK_Non_template;
3064 }
3065 
3067  TemplateArgumentLoc &AL,
3068  SmallVectorImpl<TemplateArgument> &Converted) {
3069  const TemplateArgument &Arg = AL.getArgument();
3070  QualType ArgType;
3071  TypeSourceInfo *TSI = nullptr;
3072 
3073  // Check template type parameter.
3074  switch(Arg.getKind()) {
3076  // C++ [temp.arg.type]p1:
3077  // A template-argument for a template-parameter which is a
3078  // type shall be a type-id.
3079  ArgType = Arg.getAsType();
3080  TSI = AL.getTypeSourceInfo();
3081  break;
3083  // We have a template type parameter but the template argument
3084  // is a template without any arguments.
3085  SourceRange SR = AL.getSourceRange();
3087  Diag(SR.getBegin(), diag::err_template_missing_args)
3088  << Name << SR;
3089  if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3090  Diag(Decl->getLocation(), diag::note_template_decl_here);
3091 
3092  return true;
3093  }
3095  // We have a template type parameter but the template argument is an
3096  // expression; see if maybe it is missing the "typename" keyword.
3097  CXXScopeSpec SS;
3098  DeclarationNameInfo NameInfo;
3099 
3100  if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3101  SS.Adopt(ArgExpr->getQualifierLoc());
3102  NameInfo = ArgExpr->getNameInfo();
3103  } else if (DependentScopeDeclRefExpr *ArgExpr =
3104  dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3105  SS.Adopt(ArgExpr->getQualifierLoc());
3106  NameInfo = ArgExpr->getNameInfo();
3107  } else if (CXXDependentScopeMemberExpr *ArgExpr =
3108  dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3109  if (ArgExpr->isImplicitAccess()) {
3110  SS.Adopt(ArgExpr->getQualifierLoc());
3111  NameInfo = ArgExpr->getMemberNameInfo();
3112  }
3113  }
3114 
3115  if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3116  LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3117  LookupParsedName(Result, CurScope, &SS);
3118 
3119  if (Result.getAsSingle<TypeDecl>() ||
3120  Result.getResultKind() ==
3122  // Suggest that the user add 'typename' before the NNS.
3123  SourceLocation Loc = AL.getSourceRange().getBegin();
3124  Diag(Loc, getLangOpts().MSVCCompat
3125  ? diag::ext_ms_template_type_arg_missing_typename
3126  : diag::err_template_arg_must_be_type_suggest)
3127  << FixItHint::CreateInsertion(Loc, "typename ");
3128  Diag(Param->getLocation(), diag::note_template_param_here);
3129 
3130  // Recover by synthesizing a type using the location information that we
3131  // already have.
3132  ArgType =
3134  TypeLocBuilder TLB;
3135  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3136  TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3138  TL.setNameLoc(NameInfo.getLoc());
3139  TSI = TLB.getTypeSourceInfo(Context, ArgType);
3140 
3141  // Overwrite our input TemplateArgumentLoc so that we can recover
3142  // properly.
3143  AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3145 
3146  break;
3147  }
3148  }
3149  // fallthrough
3150  }
3151  default: {
3152  // We have a template type parameter but the template argument
3153  // is not a type.
3154  SourceRange SR = AL.getSourceRange();
3155  Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3156  Diag(Param->getLocation(), diag::note_template_param_here);
3157 
3158  return true;
3159  }
3160  }
3161 
3162  if (CheckTemplateArgument(Param, TSI))
3163  return true;
3164 
3165  // Add the converted template type argument.
3166  ArgType = Context.getCanonicalType(ArgType);
3167 
3168  // Objective-C ARC:
3169  // If an explicitly-specified template argument type is a lifetime type
3170  // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3171  if (getLangOpts().ObjCAutoRefCount &&
3172  ArgType->isObjCLifetimeType() &&
3173  !ArgType.getObjCLifetime()) {
3174  Qualifiers Qs;
3176  ArgType = Context.getQualifiedType(ArgType, Qs);
3177  }
3178 
3179  Converted.push_back(TemplateArgument(ArgType));
3180  return false;
3181 }
3182 
3183 /// \brief Substitute template arguments into the default template argument for
3184 /// the given template type parameter.
3185 ///
3186 /// \param SemaRef the semantic analysis object for which we are performing
3187 /// the substitution.
3188 ///
3189 /// \param Template the template that we are synthesizing template arguments
3190 /// for.
3191 ///
3192 /// \param TemplateLoc the location of the template name that started the
3193 /// template-id we are checking.
3194 ///
3195 /// \param RAngleLoc the location of the right angle bracket ('>') that
3196 /// terminates the template-id.
3197 ///
3198 /// \param Param the template template parameter whose default we are
3199 /// substituting into.
3200 ///
3201 /// \param Converted the list of template arguments provided for template
3202 /// parameters that precede \p Param in the template parameter list.
3203 /// \returns the substituted template argument, or NULL if an error occurred.
3204 static TypeSourceInfo *
3206  TemplateDecl *Template,
3207  SourceLocation TemplateLoc,
3208  SourceLocation RAngleLoc,
3209  TemplateTypeParmDecl *Param,
3210  SmallVectorImpl<TemplateArgument> &Converted) {
3211  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3212 
3213  // If the argument type is dependent, instantiate it now based
3214  // on the previously-computed template arguments.
3215  if (ArgType->getType()->isDependentType()) {
3216  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3217  Template, Converted,
3218  SourceRange(TemplateLoc, RAngleLoc));
3219  if (Inst.isInvalid())
3220  return nullptr;
3221 
3223  Converted.data(), Converted.size());
3224 
3225  // Only substitute for the innermost template argument list.
3226  MultiLevelTemplateArgumentList TemplateArgLists;
3227  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3228  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3229  TemplateArgLists.addOuterTemplateArguments(None);
3230 
3231  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3232  ArgType =
3233  SemaRef.SubstType(ArgType, TemplateArgLists,
3234  Param->getDefaultArgumentLoc(), Param->getDeclName());
3235  }
3236 
3237  return ArgType;
3238 }
3239 
3240 /// \brief Substitute template arguments into the default template argument for
3241 /// the given non-type template parameter.
3242 ///
3243 /// \param SemaRef the semantic analysis object for which we are performing
3244 /// the substitution.
3245 ///
3246 /// \param Template the template that we are synthesizing template arguments
3247 /// for.
3248 ///
3249 /// \param TemplateLoc the location of the template name that started the
3250 /// template-id we are checking.
3251 ///
3252 /// \param RAngleLoc the location of the right angle bracket ('>') that
3253 /// terminates the template-id.
3254 ///
3255 /// \param Param the non-type template parameter whose default we are
3256 /// substituting into.
3257 ///
3258 /// \param Converted the list of template arguments provided for template
3259 /// parameters that precede \p Param in the template parameter list.
3260 ///
3261 /// \returns the substituted template argument, or NULL if an error occurred.
3262 static ExprResult
3264  TemplateDecl *Template,
3265  SourceLocation TemplateLoc,
3266  SourceLocation RAngleLoc,
3267  NonTypeTemplateParmDecl *Param,
3268  SmallVectorImpl<TemplateArgument> &Converted) {
3269  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3270  Template, Converted,
3271  SourceRange(TemplateLoc, RAngleLoc));
3272  if (Inst.isInvalid())
3273  return ExprError();
3274 
3276  Converted.data(), Converted.size());
3277 
3278  // Only substitute for the innermost template argument list.
3279  MultiLevelTemplateArgumentList TemplateArgLists;
3280  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3281  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3282  TemplateArgLists.addOuterTemplateArguments(None);
3283 
3284  EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3286  return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3287 }
3288 
3289 /// \brief Substitute template arguments into the default template argument for
3290 /// the given template template parameter.
3291 ///
3292 /// \param SemaRef the semantic analysis object for which we are performing
3293 /// the substitution.
3294 ///
3295 /// \param Template the template that we are synthesizing template arguments
3296 /// for.
3297 ///
3298 /// \param TemplateLoc the location of the template name that started the
3299 /// template-id we are checking.
3300 ///
3301 /// \param RAngleLoc the location of the right angle bracket ('>') that
3302 /// terminates the template-id.
3303 ///
3304 /// \param Param the template template parameter whose default we are
3305 /// substituting into.
3306 ///
3307 /// \param Converted the list of template arguments provided for template
3308 /// parameters that precede \p Param in the template parameter list.
3309 ///
3310 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3311 /// source-location information) that precedes the template name.
3312 ///
3313 /// \returns the substituted template argument, or NULL if an error occurred.
3314 static TemplateName
3316  TemplateDecl *Template,
3317  SourceLocation TemplateLoc,
3318  SourceLocation RAngleLoc,
3319  TemplateTemplateParmDecl *Param,
3320  SmallVectorImpl<TemplateArgument> &Converted,
3321  NestedNameSpecifierLoc &QualifierLoc) {
3322  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3323  SourceRange(TemplateLoc, RAngleLoc));
3324  if (Inst.isInvalid())
3325  return TemplateName();
3326 
3328  Converted.data(), Converted.size());
3329 
3330  // Only substitute for the innermost template argument list.
3331  MultiLevelTemplateArgumentList TemplateArgLists;
3332  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3333  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3334  TemplateArgLists.addOuterTemplateArguments(None);
3335 
3336  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3337  // Substitute into the nested-name-specifier first,
3338  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3339  if (QualifierLoc) {
3340  QualifierLoc =
3341  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3342  if (!QualifierLoc)
3343  return TemplateName();
3344  }
3345 
3346  return SemaRef.SubstTemplateName(
3347  QualifierLoc,
3350  TemplateArgLists);
3351 }
3352 
3353 /// \brief If the given template parameter has a default template
3354 /// argument, substitute into that default template argument and
3355 /// return the corresponding template argument.
3358  SourceLocation TemplateLoc,
3359  SourceLocation RAngleLoc,
3360  Decl *Param,
3362  &Converted,
3363  bool &HasDefaultArg) {
3364  HasDefaultArg = false;
3365 
3366  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3367  if (!hasVisibleDefaultArgument(TypeParm))
3368  return TemplateArgumentLoc();
3369 
3370  HasDefaultArg = true;
3371  TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3372  TemplateLoc,
3373  RAngleLoc,
3374  TypeParm,
3375  Converted);
3376  if (DI)
3377  return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3378 
3379  return TemplateArgumentLoc();
3380  }
3381 
3382  if (NonTypeTemplateParmDecl *NonTypeParm
3383  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3384  if (!hasVisibleDefaultArgument(NonTypeParm))
3385  return TemplateArgumentLoc();
3386 
3387  HasDefaultArg = true;
3388  ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3389  TemplateLoc,
3390  RAngleLoc,
3391  NonTypeParm,
3392  Converted);
3393  if (Arg.isInvalid())
3394  return TemplateArgumentLoc();
3395 
3396  Expr *ArgE = Arg.getAs<Expr>();
3397  return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3398  }
3399 
3400  TemplateTemplateParmDecl *TempTempParm
3401  = cast<TemplateTemplateParmDecl>(Param);
3402  if (!hasVisibleDefaultArgument(TempTempParm))
3403  return TemplateArgumentLoc();
3404 
3405  HasDefaultArg = true;
3406  NestedNameSpecifierLoc QualifierLoc;
3407  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3408  TemplateLoc,
3409  RAngleLoc,
3410  TempTempParm,
3411  Converted,
3412  QualifierLoc);
3413  if (TName.isNull())
3414  return TemplateArgumentLoc();
3415 
3416  return TemplateArgumentLoc(TemplateArgument(TName),
3417  TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3418  TempTempParm->getDefaultArgument().getTemplateNameLoc());
3419 }
3420 
3421 /// \brief Check that the given template argument corresponds to the given
3422 /// template parameter.
3423 ///
3424 /// \param Param The template parameter against which the argument will be
3425 /// checked.
3426 ///
3427 /// \param Arg The template argument, which may be updated due to conversions.
3428 ///
3429 /// \param Template The template in which the template argument resides.
3430 ///
3431 /// \param TemplateLoc The location of the template name for the template
3432 /// whose argument list we're matching.
3433 ///
3434 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3435 /// the template argument list.
3436 ///
3437 /// \param ArgumentPackIndex The index into the argument pack where this
3438 /// argument will be placed. Only valid if the parameter is a parameter pack.
3439 ///
3440 /// \param Converted The checked, converted argument will be added to the
3441 /// end of this small vector.
3442 ///
3443 /// \param CTAK Describes how we arrived at this particular template argument:
3444 /// explicitly written, deduced, etc.
3445 ///
3446 /// \returns true on error, false otherwise.
3448  TemplateArgumentLoc &Arg,
3449  NamedDecl *Template,
3450  SourceLocation TemplateLoc,
3451  SourceLocation RAngleLoc,
3452  unsigned ArgumentPackIndex,
3455  // Check template type parameters.
3456  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3457  return CheckTemplateTypeArgument(TTP, Arg, Converted);
3458 
3459  // Check non-type template parameters.
3460  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3461  // Do substitution on the type of the non-type template parameter
3462  // with the template arguments we've seen thus far. But if the
3463  // template has a dependent context then we cannot substitute yet.
3464  QualType NTTPType = NTTP->getType();
3465  if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3466  NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3467 
3468  if (NTTPType->isDependentType() &&
3469  !isa<TemplateTemplateParmDecl>(Template) &&
3470  !Template->getDeclContext()->isDependentContext()) {
3471  // Do substitution on the type of the non-type template parameter.
3472  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3473  NTTP, Converted,
3474  SourceRange(TemplateLoc, RAngleLoc));
3475  if (Inst.isInvalid())
3476  return true;
3477 
3479  Converted.data(), Converted.size());
3480  NTTPType = SubstType(NTTPType,
3481  MultiLevelTemplateArgumentList(TemplateArgs),
3482  NTTP->getLocation(),
3483  NTTP->getDeclName());
3484  // If that worked, check the non-type template parameter type
3485  // for validity.
3486  if (!NTTPType.isNull())
3487  NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3488  NTTP->getLocation());
3489  if (NTTPType.isNull())
3490  return true;
3491  }
3492 
3493  switch (Arg.getArgument().getKind()) {
3495  llvm_unreachable("Should never see a NULL template argument here");
3496 
3499  ExprResult Res =
3500  CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3501  Result, CTAK);
3502  if (Res.isInvalid())
3503  return true;
3504 
3505  // If the resulting expression is new, then use it in place of the
3506  // old expression in the template argument.
3507  if (Res.get() != Arg.getArgument().getAsExpr()) {
3508  TemplateArgument TA(Res.get());
3509  Arg = TemplateArgumentLoc(TA, Res.get());
3510  }
3511 
3512  Converted.push_back(Result);
3513  break;
3514  }
3515 
3519  // We've already checked this template argument, so just copy
3520  // it to the list of converted arguments.
3521  Converted.push_back(Arg.getArgument());
3522  break;
3523 
3526  // We were given a template template argument. It may not be ill-formed;
3527  // see below.
3528  if (DependentTemplateName *DTN
3531  // We have a template argument such as \c T::template X, which we
3532  // parsed as a template template argument. However, since we now
3533  // know that we need a non-type template argument, convert this
3534  // template name into an expression.
3535 
3536  DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3537  Arg.getTemplateNameLoc());
3538 
3539  CXXScopeSpec SS;
3540  SS.Adopt(Arg.getTemplateQualifierLoc());
3541  // FIXME: the template-template arg was a DependentTemplateName,
3542  // so it was provided with a template keyword. However, its source
3543  // location is not stored in the template argument structure.
3544  SourceLocation TemplateKWLoc;
3546  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3547  nullptr);
3548 
3549  // If we parsed the template argument as a pack expansion, create a
3550  // pack expansion expression.
3552  E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3553  if (E.isInvalid())
3554  return true;
3555  }
3556 
3558  E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3559  if (E.isInvalid())
3560  return true;
3561 
3562  Converted.push_back(Result);
3563  break;
3564  }
3565 
3566  // We have a template argument that actually does refer to a class
3567  // template, alias template, or template template parameter, and
3568  // therefore cannot be a non-type template argument.
3569  Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3570  << Arg.getSourceRange();
3571 
3572  Diag(Param->getLocation(), diag::note_template_param_here);
3573  return true;
3574 
3575  case TemplateArgument::Type: {
3576  // We have a non-type template parameter but the template
3577  // argument is a type.
3578 
3579  // C++ [temp.arg]p2:
3580  // In a template-argument, an ambiguity between a type-id and
3581  // an expression is resolved to a type-id, regardless of the
3582  // form of the corresponding template-parameter.
3583  //
3584  // We warn specifically about this case, since it can be rather
3585  // confusing for users.
3586  QualType T = Arg.getArgument().getAsType();
3587  SourceRange SR = Arg.getSourceRange();
3588  if (T->isFunctionType())
3589  Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3590  else
3591  Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3592  Diag(Param->getLocation(), diag::note_template_param_here);
3593  return true;
3594  }
3595 
3597  llvm_unreachable("Caller must expand template argument packs");
3598  }
3599 
3600  return false;
3601  }
3602 
3603 
3604  // Check template template parameters.
3605  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3606 
3607  // Substitute into the template parameter list of the template
3608  // template parameter, since previously-supplied template arguments
3609  // may appear within the template template parameter.
3610  {
3611  // Set up a template instantiation context.
3613  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3614  TempParm, Converted,
3615  SourceRange(TemplateLoc, RAngleLoc));
3616  if (Inst.isInvalid())
3617  return true;
3618 
3620  Converted.data(), Converted.size());
3621  TempParm = cast_or_null<TemplateTemplateParmDecl>(
3622  SubstDecl(TempParm, CurContext,
3623  MultiLevelTemplateArgumentList(TemplateArgs)));
3624  if (!TempParm)
3625  return true;
3626  }
3627 
3628  switch (Arg.getArgument().getKind()) {
3630  llvm_unreachable("Should never see a NULL template argument here");
3631 
3634  if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3635  return true;
3636 
3637  Converted.push_back(Arg.getArgument());
3638  break;
3639 
3642  // We have a template template parameter but the template
3643  // argument does not refer to a template.
3644  Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3645  << getLangOpts().CPlusPlus11;
3646  return true;
3647 
3649  llvm_unreachable("Declaration argument with template template parameter");
3651  llvm_unreachable("Integral argument with template template parameter");
3653  llvm_unreachable("Null pointer argument with template template parameter");
3654 
3656  llvm_unreachable("Caller must expand template argument packs");
3657  }
3658 
3659  return false;
3660 }
3661 
3662 /// \brief Diagnose an arity mismatch in the
3663 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3664  SourceLocation TemplateLoc,
3665  TemplateArgumentListInfo &TemplateArgs) {
3666  TemplateParameterList *Params = Template->getTemplateParameters();
3667  unsigned NumParams = Params->size();
3668  unsigned NumArgs = TemplateArgs.size();
3669 
3670  SourceRange Range;
3671  if (NumArgs > NumParams)
3672  Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3673  TemplateArgs.getRAngleLoc());
3674  S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3675  << (NumArgs > NumParams)
3676  << (isa<ClassTemplateDecl>(Template)? 0 :
3677  isa<FunctionTemplateDecl>(Template)? 1 :
3678  isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3679  << Template << Range;
3680  S.Diag(Template->getLocation(), diag::note_template_decl_here)
3681  << Params->getSourceRange();
3682  return true;
3683 }
3684 
3685 /// \brief Check whether the template parameter is a pack expansion, and if so,
3686 /// determine the number of parameters produced by that expansion. For instance:
3687 ///
3688 /// \code
3689 /// template<typename ...Ts> struct A {
3690 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3691 /// };
3692 /// \endcode
3693 ///
3694 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3695 /// is not a pack expansion, so returns an empty Optional.
3697  if (NonTypeTemplateParmDecl *NTTP
3698  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3699  if (NTTP->isExpandedParameterPack())
3700  return NTTP->getNumExpansionTypes();
3701  }
3702 
3703  if (TemplateTemplateParmDecl *TTP
3704  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3705  if (TTP->isExpandedParameterPack())
3706  return TTP->getNumExpansionTemplateParameters();
3707  }
3708 
3709  return None;
3710 }
3711 
3712 /// Diagnose a missing template argument.
3713 template<typename TemplateParmDecl>
3715  TemplateDecl *TD,
3716  const TemplateParmDecl *D,
3717  TemplateArgumentListInfo &Args) {
3718  // Dig out the most recent declaration of the template parameter; there may be
3719  // declarations of the template that are more recent than TD.
3720  D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3721  ->getTemplateParameters()
3722  ->getParam(D->getIndex()));
3723 
3724  // If there's a default argument that's not visible, diagnose that we're
3725  // missing a module import.
3727  if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3728  S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3729  D->getDefaultArgumentLoc(), Modules,
3731  /*Recover*/ true);
3732  return true;
3733  }
3734 
3735  // FIXME: If there's a more recent default argument that *is* visible,
3736  // diagnose that it was declared too late.
3737 
3738  return diagnoseArityMismatch(S, TD, Loc, Args);
3739 }
3740 
3741 /// \brief Check that the given template argument list is well-formed
3742 /// for specializing the given template.
3744  SourceLocation TemplateLoc,
3745  TemplateArgumentListInfo &TemplateArgs,
3746  bool PartialTemplateArgs,
3747  SmallVectorImpl<TemplateArgument> &Converted) {
3748  // Make a copy of the template arguments for processing. Only make the
3749  // changes at the end when successful in matching the arguments to the
3750  // template.
3751  TemplateArgumentListInfo NewArgs = TemplateArgs;
3752 
3753  TemplateParameterList *Params = Template->getTemplateParameters();
3754 
3755  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3756 
3757  // C++ [temp.arg]p1:
3758  // [...] The type and form of each template-argument specified in
3759  // a template-id shall match the type and form specified for the
3760  // corresponding parameter declared by the template in its
3761  // template-parameter-list.
3762  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3763  SmallVector<TemplateArgument, 2> ArgumentPack;
3764  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3765  LocalInstantiationScope InstScope(*this, true);
3766  for (TemplateParameterList::iterator Param = Params->begin(),
3767  ParamEnd = Params->end();
3768  Param != ParamEnd; /* increment in loop */) {
3769  // If we have an expanded parameter pack, make sure we don't have too
3770  // many arguments.
3771  if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3772  if (*Expansions == ArgumentPack.size()) {
3773  // We're done with this parameter pack. Pack up its arguments and add
3774  // them to the list.
3775  Converted.push_back(
3776  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3777  ArgumentPack.clear();
3778 
3779  // This argument is assigned to the next parameter.
3780  ++Param;
3781  continue;
3782  } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3783  // Not enough arguments for this parameter pack.
3784  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3785  << false
3786  << (isa<ClassTemplateDecl>(Template)? 0 :
3787  isa<FunctionTemplateDecl>(Template)? 1 :
3788  isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3789  << Template;
3790  Diag(Template->getLocation(), diag::note_template_decl_here)
3791  << Params->getSourceRange();
3792  return true;
3793  }
3794  }
3795 
3796  if (ArgIdx < NumArgs) {
3797  // Check the template argument we were given.
3798  if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3799  TemplateLoc, RAngleLoc,
3800  ArgumentPack.size(), Converted))
3801  return true;
3802 
3803  bool PackExpansionIntoNonPack =
3804  NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3805  (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3806  if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3807  // Core issue 1430: we have a pack expansion as an argument to an
3808  // alias template, and it's not part of a parameter pack. This
3809  // can't be canonicalized, so reject it now.
3810  Diag(NewArgs[ArgIdx].getLocation(),
3811  diag::err_alias_template_expansion_into_fixed_list)
3812  << NewArgs[ArgIdx].getSourceRange();
3813  Diag((*Param)->getLocation(), diag::note_template_param_here);
3814  return true;
3815  }
3816 
3817  // We're now done with this argument.
3818  ++ArgIdx;
3819 
3820  if ((*Param)->isTemplateParameterPack()) {
3821  // The template parameter was a template parameter pack, so take the
3822  // deduced argument and place it on the argument pack. Note that we
3823  // stay on the same template parameter so that we can deduce more
3824  // arguments.
3825  ArgumentPack.push_back(Converted.pop_back_val());
3826  } else {
3827  // Move to the next template parameter.
3828  ++Param;
3829  }
3830 
3831  // If we just saw a pack expansion into a non-pack, then directly convert
3832  // the remaining arguments, because we don't know what parameters they'll
3833  // match up with.
3834  if (PackExpansionIntoNonPack) {
3835  if (!ArgumentPack.empty()) {
3836  // If we were part way through filling in an expanded parameter pack,
3837  // fall back to just producing individual arguments.
3838  Converted.insert(Converted.end(),
3839  ArgumentPack.begin(), ArgumentPack.end());
3840  ArgumentPack.clear();
3841  }
3842 
3843  while (ArgIdx < NumArgs) {
3844  Converted.push_back(NewArgs[ArgIdx].getArgument());
3845  ++ArgIdx;
3846  }
3847 
3848  return false;
3849  }
3850 
3851  continue;
3852  }
3853 
3854  // If we're checking a partial template argument list, we're done.
3855  if (PartialTemplateArgs) {
3856  if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3857  Converted.push_back(
3858  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3859 
3860  return false;
3861  }
3862 
3863  // If we have a template parameter pack with no more corresponding
3864  // arguments, just break out now and we'll fill in the argument pack below.
3865  if ((*Param)->isTemplateParameterPack()) {
3866  assert(!getExpandedPackSize(*Param) &&
3867  "Should have dealt with this already");
3868 
3869  // A non-expanded parameter pack before the end of the parameter list
3870  // only occurs for an ill-formed template parameter list, unless we've
3871  // got a partial argument list for a function template, so just bail out.
3872  if (Param + 1 != ParamEnd)
3873  return true;
3874 
3875  Converted.push_back(
3876  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3877  ArgumentPack.clear();
3878 
3879  ++Param;
3880  continue;
3881  }
3882 
3883  // Check whether we have a default argument.
3884  TemplateArgumentLoc Arg;
3885 
3886  // Retrieve the default template argument from the template
3887  // parameter. For each kind of template parameter, we substitute the
3888  // template arguments provided thus far and any "outer" template arguments
3889  // (when the template parameter was part of a nested template) into
3890  // the default argument.
3891  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3892  if (!hasVisibleDefaultArgument(TTP))
3893  return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3894  NewArgs);
3895 
3897  Template,
3898  TemplateLoc,
3899  RAngleLoc,
3900  TTP,
3901  Converted);
3902  if (!ArgType)
3903  return true;
3904 
3905  Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3906  ArgType);
3907  } else if (NonTypeTemplateParmDecl *NTTP
3908  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3909  if (!hasVisibleDefaultArgument(NTTP))
3910  return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3911  NewArgs);
3912 
3913  ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3914  TemplateLoc,
3915  RAngleLoc,
3916  NTTP,
3917  Converted);
3918  if (E.isInvalid())
3919  return true;
3920 
3921  Expr *Ex = E.getAs<Expr>();
3922  Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3923  } else {
3924  TemplateTemplateParmDecl *TempParm
3925  = cast<TemplateTemplateParmDecl>(*Param);
3926 
3927  if (!hasVisibleDefaultArgument(TempParm))
3928  return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3929  NewArgs);
3930 
3931  NestedNameSpecifierLoc QualifierLoc;
3933  TemplateLoc,
3934  RAngleLoc,
3935  TempParm,
3936  Converted,
3937  QualifierLoc);
3938  if (Name.isNull())
3939  return true;
3940 
3941  Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3942  TempParm->getDefaultArgument().getTemplateNameLoc());
3943  }
3944 
3945  // Introduce an instantiation record that describes where we are using
3946  // the default template argument.
3947  InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3948  SourceRange(TemplateLoc, RAngleLoc));
3949  if (Inst.isInvalid())
3950  return true;
3951 
3952  // Check the default template argument.
3953  if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3954  RAngleLoc, 0, Converted))
3955  return true;
3956 
3957  // Core issue 150 (assumed resolution): if this is a template template
3958  // parameter, keep track of the default template arguments from the
3959  // template definition.
3960  if (isTemplateTemplateParameter)
3961  NewArgs.addArgument(Arg);
3962 
3963  // Move to the next template parameter and argument.
3964  ++Param;
3965  ++ArgIdx;
3966  }
3967 
3968  // If we're performing a partial argument substitution, allow any trailing
3969  // pack expansions; they might be empty. This can happen even if
3970  // PartialTemplateArgs is false (the list of arguments is complete but
3971  // still dependent).
3972  if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3973  CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3974  while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3975  Converted.push_back(NewArgs[ArgIdx++].getArgument());
3976  }
3977 
3978  // If we have any leftover arguments, then there were too many arguments.
3979  // Complain and fail.
3980  if (ArgIdx < NumArgs)
3981  return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3982 
3983  // No problems found with the new argument list, propagate changes back
3984  // to caller.
3985  TemplateArgs = std::move(NewArgs);
3986 
3987  return false;
3988 }
3989 
3990 namespace {
3991  class UnnamedLocalNoLinkageFinder
3992  : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3993  {
3994  Sema &S;
3995  SourceRange SR;
3996 
3998 
3999  public:
4000  UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4001 
4002  bool Visit(QualType T) {
4003  return inherited::Visit(T.getTypePtr());
4004  }
4005 
4006 #define TYPE(Class, Parent) \
4007  bool Visit##Class##Type(const Class##Type *);
4008 #define ABSTRACT_TYPE(Class, Parent) \
4009  bool Visit##Class##Type(const Class##Type *) { return false; }
4010 #define NON_CANONICAL_TYPE(Class, Parent) \
4011  bool Visit##Class##Type(const Class##Type *) { return false; }
4012 #include "clang/AST/TypeNodes.def"
4013 
4014  bool VisitTagDecl(const TagDecl *Tag);
4015  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4016  };
4017 }
4018 
4019 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4020  return false;
4021 }
4022 
4023 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4024  return Visit(T->getElementType());
4025 }
4026 
4027 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4028  return Visit(T->getPointeeType());
4029 }
4030 
4031 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4032  const BlockPointerType* T) {
4033  return Visit(T->getPointeeType());
4034 }
4035 
4036 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4037  const LValueReferenceType* T) {
4038  return Visit(T->getPointeeType());
4039 }
4040 
4041 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4042  const RValueReferenceType* T) {
4043  return Visit(T->getPointeeType());
4044 }
4045 
4046 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4047  const MemberPointerType* T) {
4048  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4049 }
4050 
4051 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4052  const ConstantArrayType* T) {
4053  return Visit(T->getElementType());
4054 }
4055 
4056 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4057  const IncompleteArrayType* T) {
4058  return Visit(T->getElementType());
4059 }
4060 
4061 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4062  const VariableArrayType* T) {
4063  return Visit(T->getElementType());
4064 }
4065 
4066 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4067  const DependentSizedArrayType* T) {
4068  return Visit(T->getElementType());
4069 }
4070 
4071 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4072  const DependentSizedExtVectorType* T) {
4073  return Visit(T->getElementType());
4074 }
4075 
4076 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4077  return Visit(T->getElementType());
4078 }
4079 
4080 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4081  return Visit(T->getElementType());
4082 }
4083 
4084 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4085  const FunctionProtoType* T) {
4086  for (const auto &A : T->param_types()) {
4087  if (Visit(A))
4088  return true;
4089  }
4090 
4091  return Visit(T->getReturnType());
4092 }
4093 
4094 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4095  const FunctionNoProtoType* T) {
4096  return Visit(T->getReturnType());
4097 }
4098 
4099 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4100  const UnresolvedUsingType*) {
4101  return false;
4102 }
4103 
4104 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4105  return false;
4106 }
4107 
4108 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4109  return Visit(T->getUnderlyingType());
4110 }
4111 
4112 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4113  return false;
4114 }
4115 
4116 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4117  const UnaryTransformType*) {
4118  return false;
4119 }
4120 
4121 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4122  return Visit(T->getDeducedType());
4123 }
4124 
4125 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4126  return VisitTagDecl(T->getDecl());
4127 }
4128 
4129 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4130  return VisitTagDecl(T->getDecl());
4131 }
4132 
4133 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4134  const TemplateTypeParmType*) {
4135  return false;
4136 }
4137 
4138 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4140  return false;
4141 }
4142 
4143 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4144  const TemplateSpecializationType*) {
4145  return false;
4146 }
4147 
4148 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4149  const InjectedClassNameType* T) {
4150  return VisitTagDecl(T->getDecl());
4151 }
4152 
4153 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4154  const DependentNameType* T) {
4155  return VisitNestedNameSpecifier(T->getQualifier());
4156 }
4157 
4158 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4160  return VisitNestedNameSpecifier(T->getQualifier());
4161 }
4162 
4163 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4164  const PackExpansionType* T) {
4165  return Visit(T->getPattern());
4166 }
4167 
4168 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4169  return false;
4170 }
4171 
4172 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4173  const ObjCInterfaceType *) {
4174  return false;
4175 }
4176 
4177 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4178  const ObjCObjectPointerType *) {
4179  return false;
4180 }
4181 
4182 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4183  return Visit(T->getValueType());
4184 }
4185 
4186 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4187  return false;
4188 }
4189 
4190 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4191  if (Tag->getDeclContext()->isFunctionOrMethod()) {
4192  S.Diag(SR.getBegin(),
4193  S.getLangOpts().CPlusPlus11 ?
4194  diag::warn_cxx98_compat_template_arg_local_type :
4195  diag::ext_template_arg_local_type)
4196  << S.Context.getTypeDeclType(Tag) << SR;
4197  return true;
4198  }
4199 
4200  if (!Tag->hasNameForLinkage()) {
4201  S.Diag(SR.getBegin(),
4202  S.getLangOpts().CPlusPlus11 ?
4203  diag::warn_cxx98_compat_template_arg_unnamed_type :
4204  diag::ext_template_arg_unnamed_type) << SR;
4205  S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4206  return true;
4207  }
4208 
4209  return false;
4210 }
4211 
4212 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4213  NestedNameSpecifier *NNS) {
4214  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4215  return true;
4216 
4217  switch (NNS->getKind()) {
4223  return false;
4224 
4227  return Visit(QualType(NNS->getAsType(), 0));
4228  }
4229  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4230 }
4231 
4232 
4233 /// \brief Check a template argument against its corresponding
4234 /// template type parameter.
4235 ///
4236 /// This routine implements the semantics of C++ [temp.arg.type]. It
4237 /// returns true if an error occurred, and false otherwise.
4239  TypeSourceInfo *ArgInfo) {
4240  assert(ArgInfo && "invalid TypeSourceInfo");
4241  QualType Arg = ArgInfo->getType();
4242  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4243 
4244  if (Arg->isVariablyModifiedType()) {
4245  return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4246  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4247  return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4248  }
4249 
4250  // C++03 [temp.arg.type]p2:
4251  // A local type, a type with no linkage, an unnamed type or a type
4252  // compounded from any of these types shall not be used as a
4253  // template-argument for a template type-parameter.
4254  //
4255  // C++11 allows these, and even in C++03 we allow them as an extension with
4256  // a warning.
4257  bool NeedsCheck;
4258  if (LangOpts.CPlusPlus11)
4259  NeedsCheck =
4260  !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4261  SR.getBegin()) ||
4262  !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4263  SR.getBegin());
4264  else
4265  NeedsCheck = Arg->hasUnnamedOrLocalType();
4266 
4267  if (NeedsCheck) {
4268  UnnamedLocalNoLinkageFinder Finder(*this, SR);
4269  (void)Finder.Visit(Context.getCanonicalType(Arg));
4270  }
4271 
4272  return false;
4273 }
4274 
4279 };
4280 
4281 /// \brief Determine whether the given template argument is a null pointer
4282 /// value of the appropriate type.
4283 static NullPointerValueKind
4285  QualType ParamType, Expr *Arg) {
4286  if (Arg->isValueDependent() || Arg->isTypeDependent())
4287  return NPV_NotNullPointer;
4288 
4289  if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
4290  llvm_unreachable(
4291  "Incomplete parameter type in isNullPointerValueTemplateArgument!");
4292 
4293  if (!S.getLangOpts().CPlusPlus11)
4294  return NPV_NotNullPointer;
4295 
4296  // Determine whether we have a constant expression.
4298  if (ArgRV.isInvalid())
4299  return NPV_Error;
4300  Arg = ArgRV.get();
4301 
4302  Expr::EvalResult EvalResult;
4304  EvalResult.Diag = &Notes;
4305  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4306  EvalResult.HasSideEffects) {
4307  SourceLocation DiagLoc = Arg->getExprLoc();
4308 
4309  // If our only note is the usual "invalid subexpression" note, just point
4310  // the caret at its location rather than producing an essentially
4311  // redundant note.
4312  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4313  diag::note_invalid_subexpr_in_const_expr) {
4314  DiagLoc = Notes[0].first;
4315  Notes.clear();
4316  }
4317 
4318  S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4319  << Arg->getType() << Arg->getSourceRange();
4320  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4321  S.Diag(Notes[I].first, Notes[I].second);
4322 
4323  S.Diag(Param->getLocation(), diag::note_template_param_here);
4324  return NPV_Error;
4325  }
4326 
4327  // C++11 [temp.arg.nontype]p1:
4328  // - an address constant expression of type std::nullptr_t
4329  if (Arg->getType()->isNullPtrType())
4330  return NPV_NullPointer;
4331 
4332  // - a constant expression that evaluates to a null pointer value (4.10); or
4333  // - a constant expression that evaluates to a null member pointer value
4334  // (4.11); or
4335  if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4336  (EvalResult.Val.isMemberPointer() &&
4337  !EvalResult.Val.getMemberPointerDecl())) {
4338  // If our expression has an appropriate type, we've succeeded.
4339  bool ObjCLifetimeConversion;
4340  if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4341  S.IsQualificationConversion(Arg->getType(), ParamType, false,
4342  ObjCLifetimeConversion))
4343  return NPV_NullPointer;
4344 
4345  // The types didn't match, but we know we got a null pointer; complain,
4346  // then recover as if the types were correct.
4347  S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4348  << Arg->getType() << ParamType << Arg->getSourceRange();
4349  S.Diag(Param->getLocation(), diag::note_template_param_here);
4350  return NPV_NullPointer;
4351  }
4352 
4353  // If we don't have a null pointer value, but we do have a NULL pointer
4354  // constant, suggest a cast to the appropriate type.
4356  std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4357  S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4358  << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4359  << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4360  ")");
4361  S.Diag(Param->getLocation(), diag::note_template_param_here);
4362  return NPV_NullPointer;
4363  }
4364 
4365  // FIXME: If we ever want to support general, address-constant expressions
4366  // as non-type template arguments, we should return the ExprResult here to
4367  // be interpreted by the caller.
4368  return NPV_NotNullPointer;
4369 }
4370 
4371 /// \brief Checks whether the given template argument is compatible with its
4372 /// template parameter.
4374  Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4375  Expr *Arg, QualType ArgType) {
4376  bool ObjCLifetimeConversion;
4377  if (ParamType->isPointerType() &&
4378  !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4379  S.IsQualificationConversion(ArgType, ParamType, false,
4380  ObjCLifetimeConversion)) {
4381  // For pointer-to-object types, qualification conversions are
4382  // permitted.
4383  } else {
4384  if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4385  if (!ParamRef->getPointeeType()->isFunctionType()) {
4386  // C++ [temp.arg.nontype]p5b3:
4387  // For a non-type template-parameter of type reference to
4388  // object, no conversions apply. The type referred to by the
4389  // reference may be more cv-qualified than the (otherwise
4390  // identical) type of the template- argument. The
4391  // template-parameter is bound directly to the
4392  // template-argument, which shall be an lvalue.
4393 
4394  // FIXME: Other qualifiers?
4395  unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4396  unsigned ArgQuals = ArgType.getCVRQualifiers();
4397 
4398  if ((ParamQuals | ArgQuals) != ParamQuals) {
4399  S.Diag(Arg->getLocStart(),
4400  diag::err_template_arg_ref_bind_ignores_quals)
4401  << ParamType << Arg->getType() << Arg->getSourceRange();
4402  S.Diag(Param->getLocation(), diag::note_template_param_here);
4403  return true;
4404  }
4405  }
4406  }
4407 
4408  // At this point, the template argument refers to an object or
4409  // function with external linkage. We now need to check whether the
4410  // argument and parameter types are compatible.
4411  if (!S.Context.hasSameUnqualifiedType(ArgType,
4412  ParamType.getNonReferenceType())) {
4413  // We can't perform this conversion or binding.
4414  if (ParamType->isReferenceType())
4415  S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4416  << ParamType << ArgIn->getType() << Arg->getSourceRange();
4417  else
4418  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4419  << ArgIn->getType() << ParamType << Arg->getSourceRange();
4420  S.Diag(Param->getLocation(), diag::note_template_param_here);
4421  return true;
4422  }
4423  }
4424 
4425  return false;
4426 }
4427 
4428 /// \brief Checks whether the given template argument is the address
4429 /// of an object or function according to C++ [temp.arg.nontype]p1.
4430 static bool
4432  NonTypeTemplateParmDecl *Param,
4433  QualType ParamType,
4434  Expr *ArgIn,
4435  TemplateArgument &Converted) {
4436  bool Invalid = false;
4437  Expr *Arg = ArgIn;
4438  QualType ArgType = Arg->getType();
4439 
4440  bool AddressTaken = false;
4441  SourceLocation AddrOpLoc;
4442  if (S.getLangOpts().MicrosoftExt) {
4443  // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4444  // dereference and address-of operators.
4445  Arg = Arg->IgnoreParenCasts();
4446 
4447  bool ExtWarnMSTemplateArg = false;
4448  UnaryOperatorKind FirstOpKind;
4449  SourceLocation FirstOpLoc;
4450  while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4451  UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4452  if (UnOpKind == UO_Deref)
4453  ExtWarnMSTemplateArg = true;
4454  if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4455  Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4456  if (!AddrOpLoc.isValid()) {
4457  FirstOpKind = UnOpKind;
4458  FirstOpLoc = UnOp->getOperatorLoc();
4459  }
4460  } else
4461  break;
4462  }
4463  if (FirstOpLoc.isValid()) {
4464  if (ExtWarnMSTemplateArg)
4465  S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4466  << ArgIn->getSourceRange();
4467 
4468  if (FirstOpKind == UO_AddrOf)
4469  AddressTaken = true;
4470  else if (Arg->getType()->isPointerType()) {
4471  // We cannot let pointers get dereferenced here, that is obviously not a
4472  // constant expression.
4473  assert(FirstOpKind == UO_Deref);
4474  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4475  << Arg->getSourceRange();
4476  }
4477  }
4478  } else {
4479  // See through any implicit casts we added to fix the type.
4480  Arg = Arg->IgnoreImpCasts();
4481 
4482  // C++ [temp.arg.nontype]p1:
4483  //
4484  // A template-argument for a non-type, non-template
4485  // template-parameter shall be one of: [...]
4486  //
4487  // -- the address of an object or function with external
4488  // linkage, including function templates and function
4489  // template-ids but excluding non-static class members,
4490  // expressed as & id-expression where the & is optional if
4491  // the name refers to a function or array, or if the
4492  // corresponding template-parameter is a reference; or
4493 
4494  // In C++98/03 mode, give an extension warning on any extra parentheses.
4495  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4496  bool ExtraParens = false;
4497  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4498  if (!Invalid && !ExtraParens) {
4499  S.Diag(Arg->getLocStart(),
4500  S.getLangOpts().CPlusPlus11
4501  ? diag::warn_cxx98_compat_template_arg_extra_parens
4502  : diag::ext_template_arg_extra_parens)
4503  << Arg->getSourceRange();
4504  ExtraParens = true;
4505  }
4506 
4507  Arg = Parens->getSubExpr();
4508  }
4509 
4510  while (SubstNonTypeTemplateParmExpr *subst =
4511  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4512  Arg = subst->getReplacement()->IgnoreImpCasts();
4513 
4514  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4515  if (UnOp->getOpcode() == UO_AddrOf) {
4516  Arg = UnOp->getSubExpr();
4517  AddressTaken = true;
4518  AddrOpLoc = UnOp->getOperatorLoc();
4519  }
4520  }
4521 
4522  while (SubstNonTypeTemplateParmExpr *subst =
4523  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4524  Arg = subst->getReplacement()->IgnoreImpCasts();
4525  }
4526 
4527  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4528  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4529 
4530  // If our parameter has pointer type, check for a null template value.
4531  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4533  // dllimport'd entities aren't constant but are available inside of template
4534  // arguments.
4535  if (Entity && Entity->hasAttr<DLLImportAttr>())
4536  NPV = NPV_NotNullPointer;
4537  else
4538  NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4539  switch (NPV) {
4540  case NPV_NullPointer:
4541  S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4542  Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4543  /*isNullPtr=*/true);
4544  return false;
4545 
4546  case NPV_Error:
4547  return true;
4548 
4549  case NPV_NotNullPointer:
4550  break;
4551  }
4552  }
4553 
4554  // Stop checking the precise nature of the argument if it is value dependent,
4555  // it should be checked when instantiated.
4556  if (Arg->isValueDependent()) {
4557  Converted = TemplateArgument(ArgIn);
4558  return false;
4559  }
4560 
4561  if (isa<CXXUuidofExpr>(Arg)) {
4562  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4563  ArgIn, Arg, ArgType))
4564  return true;
4565 
4566  Converted = TemplateArgument(ArgIn);
4567  return false;
4568  }
4569 
4570  if (!DRE) {
4571  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4572  << Arg->getSourceRange();
4573  S.Diag(Param->getLocation(), diag::note_template_param_here);
4574  return true;
4575  }
4576 
4577  // Cannot refer to non-static data members
4578  if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4579  S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4580  << Entity << Arg->getSourceRange();
4581  S.Diag(Param->getLocation(), diag::note_template_param_here);
4582  return true;
4583  }
4584 
4585  // Cannot refer to non-static member functions
4586  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4587  if (!Method->isStatic()) {
4588  S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4589  << Method << Arg->getSourceRange();
4590  S.Diag(Param->getLocation(), diag::note_template_param_here);
4591  return true;
4592  }
4593  }
4594 
4595  FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4596  VarDecl *Var = dyn_cast<VarDecl>(Entity);
4597 
4598  // A non-type template argument must refer to an object or function.
4599  if (!Func && !Var) {
4600  // We found something, but we don't know specifically what it is.
4601  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4602  << Arg->getSourceRange();
4603  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4604  return true;
4605  }
4606 
4607  // Address / reference template args must have external linkage in C++98.
4608  if (Entity->getFormalLinkage() == InternalLinkage) {
4609  S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4610  diag::warn_cxx98_compat_template_arg_object_internal :
4611  diag::ext_template_arg_object_internal)
4612  << !Func << Entity << Arg->getSourceRange();
4613  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4614  << !Func;
4615  } else if (!Entity->hasLinkage()) {
4616  S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4617  << !Func << Entity << Arg->getSourceRange();
4618  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4619  << !Func;
4620  return true;
4621  }
4622 
4623  if (Func) {
4624  // If the template parameter has pointer type, the function decays.
4625  if (ParamType->isPointerType() && !AddressTaken)
4626  ArgType = S.Context.getPointerType(Func->getType());
4627  else if (AddressTaken && ParamType->isReferenceType()) {
4628  // If we originally had an address-of operator, but the
4629  // parameter has reference type, complain and (if things look
4630  // like they will work) drop the address-of operator.
4631  if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4632  ParamType.getNonReferenceType())) {
4633  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4634  << ParamType;
4635  S.Diag(Param->getLocation(), diag::note_template_param_here);
4636  return true;
4637  }
4638 
4639  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4640  << ParamType
4641  << FixItHint::CreateRemoval(AddrOpLoc);
4642  S.Diag(Param->getLocation(), diag::note_template_param_here);
4643 
4644  ArgType = Func->getType();
4645  }
4646  } else {
4647  // A value of reference type is not an object.
4648  if (Var->getType()->isReferenceType()) {
4649  S.Diag(Arg->getLocStart(),
4650  diag::err_template_arg_reference_var)
4651  << Var->getType() << Arg->getSourceRange();
4652  S.Diag(Param->getLocation(), diag::note_template_param_here);
4653  return true;
4654  }
4655 
4656  // A template argument must have static storage duration.
4657  if (Var->getTLSKind()) {
4658  S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4659  << Arg->getSourceRange();
4660  S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4661  return true;
4662  }
4663 
4664  // If the template parameter has pointer type, we must have taken
4665  // the address of this object.
4666  if (ParamType->isReferenceType()) {
4667  if (AddressTaken) {
4668  // If we originally had an address-of operator, but the
4669  // parameter has reference type, complain and (if things look
4670  // like they will work) drop the address-of operator.
4671  if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4672  ParamType.getNonReferenceType())) {
4673  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4674  << ParamType;
4675  S.Diag(Param->getLocation(), diag::note_template_param_here);
4676  return true;
4677  }
4678 
4679  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4680  << ParamType
4681  << FixItHint::CreateRemoval(AddrOpLoc);
4682  S.Diag(Param->getLocation(), diag::note_template_param_here);
4683 
4684  ArgType = Var->getType();
4685  }
4686  } else if (!AddressTaken && ParamType->isPointerType()) {
4687  if (Var->getType()->isArrayType()) {
4688  // Array-to-pointer decay.
4689  ArgType = S.Context.getArrayDecayedType(Var->getType());
4690  } else {
4691  // If the template parameter has pointer type but the address of
4692  // this object was not taken, complain and (possibly) recover by
4693  // taking the address of the entity.
4694  ArgType = S.Context.getPointerType(Var->getType());
4695  if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4696  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4697  << ParamType;
4698  S.Diag(Param->getLocation(), diag::note_template_param_here);
4699  return true;
4700  }
4701 
4702  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4703  << ParamType
4704  << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4705 
4706  S.Diag(Param->getLocation(), diag::note_template_param_here);
4707  }
4708  }
4709  }
4710 
4711  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4712  Arg, ArgType))
4713  return true;
4714 
4715  // Create the template argument.
4716  Converted =
4717  TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4718  S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4719  return false;
4720 }
4721 
4722 /// \brief Checks whether the given template argument is a pointer to
4723 /// member constant according to C++ [temp.arg.nontype]p1.
4725  NonTypeTemplateParmDecl *Param,
4726  QualType ParamType,
4727  Expr *&ResultArg,
4728  TemplateArgument &Converted) {
4729  bool Invalid = false;
4730 
4731  // Check for a null pointer value.
4732  Expr *Arg = ResultArg;
4733  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4734  case NPV_Error:
4735  return true;
4736  case NPV_NullPointer:
4737  S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4738  Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4739  /*isNullPtr*/true);
4740  return false;
4741  case NPV_NotNullPointer:
4742  break;
4743  }
4744 
4745  bool ObjCLifetimeConversion;
4746  if (S.IsQualificationConversion(Arg->getType(),
4747  ParamType.getNonReferenceType(),
4748  false, ObjCLifetimeConversion)) {
4749  Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4750  Arg->getValueKind()).get();
4751  ResultArg = Arg;
4752  } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4753  ParamType.getNonReferenceType())) {
4754  // We can't perform this conversion.
4755  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4756  << Arg->getType() << ParamType << Arg->getSourceRange();
4757  S.Diag(Param->getLocation(), diag::note_template_param_here);
4758  return true;
4759  }
4760 
4761  // See through any implicit casts we added to fix the type.
4762  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4763  Arg = Cast->getSubExpr();
4764 
4765  // C++ [temp.arg.nontype]p1:
4766  //
4767  // A template-argument for a non-type, non-template
4768  // template-parameter shall be one of: [...]
4769  //
4770  // -- a pointer to member expressed as described in 5.3.1.
4771  DeclRefExpr *DRE = nullptr;
4772 
4773  // In C++98/03 mode, give an extension warning on any extra parentheses.
4774  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4775  bool ExtraParens = false;
4776  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4777  if (!Invalid && !ExtraParens) {
4778  S.Diag(Arg->getLocStart(),
4779  S.getLangOpts().CPlusPlus11 ?
4780  diag::warn_cxx98_compat_template_arg_extra_parens :
4781  diag::ext_template_arg_extra_parens)
4782  << Arg->getSourceRange();
4783  ExtraParens = true;
4784  }
4785 
4786  Arg = Parens->getSubExpr();
4787  }
4788 
4789  while (SubstNonTypeTemplateParmExpr *subst =
4790  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4791  Arg = subst->getReplacement()->IgnoreImpCasts();
4792 
4793  // A pointer-to-member constant written &Class::member.
4794  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4795  if (UnOp->getOpcode() == UO_AddrOf) {
4796  DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4797  if (DRE && !DRE->getQualifier())
4798  DRE = nullptr;
4799  }
4800  }
4801  // A constant of pointer-to-member type.
4802  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4803  if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4804  if (VD->getType()->isMemberPointerType()) {
4805  if (isa<NonTypeTemplateParmDecl>(VD)) {
4806  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4807  Converted = TemplateArgument(Arg);
4808  } else {
4809  VD = cast<ValueDecl>(VD->getCanonicalDecl());
4810  Converted = TemplateArgument(VD, ParamType);
4811  }
4812  return Invalid;
4813  }
4814  }
4815  }
4816 
4817  DRE = nullptr;
4818  }
4819 
4820  if (!DRE)
4821  return S.Diag(Arg->getLocStart(),
4822  diag::err_template_arg_not_pointer_to_member_form)
4823  << Arg->getSourceRange();
4824 
4825  if (isa<FieldDecl>(DRE->getDecl()) ||
4826  isa<IndirectFieldDecl>(DRE->getDecl()) ||
4827  isa<CXXMethodDecl>(DRE->getDecl())) {
4828  assert((isa<FieldDecl>(DRE->getDecl()) ||
4829  isa<IndirectFieldDecl>(DRE->getDecl()) ||
4830  !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4831  "Only non-static member pointers can make it here");
4832 
4833  // Okay: this is the address of a non-static member, and therefore
4834  // a member pointer constant.
4835  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4836  Converted = TemplateArgument(Arg);
4837  } else {
4838  ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4839  Converted = TemplateArgument(D, ParamType);
4840  }
4841  return Invalid;
4842  }
4843 
4844  // We found something else, but we don't know specifically what it is.
4845  S.Diag(Arg->getLocStart(),
4846  diag::err_template_arg_not_pointer_to_member_form)
4847  << Arg->getSourceRange();
4848  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4849  return true;
4850 }
4851 
4852 /// \brief Check a template argument against its corresponding
4853 /// non-type template parameter.
4854 ///
4855 /// This routine implements the semantics of C++ [temp.arg.nontype].
4856 /// If an error occurred, it returns ExprError(); otherwise, it
4857 /// returns the converted template argument. \p ParamType is the
4858 /// type of the non-type template parameter after it has been instantiated.
4860  QualType ParamType, Expr *Arg,
4861  TemplateArgument &Converted,
4863  SourceLocation StartLoc = Arg->getLocStart();
4864 
4865  // If either the parameter has a dependent type or the argument is
4866  // type-dependent, there's nothing we can check now.
4867  if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4868  // FIXME: Produce a cloned, canonical expression?
4869  Converted = TemplateArgument(Arg);
4870  return Arg;
4871  }
4872 
4873  // We should have already dropped all cv-qualifiers by now.
4874  assert(!ParamType.hasQualifiers() &&
4875  "non-type template parameter type cannot be qualified");
4876 
4877  if (CTAK == CTAK_Deduced &&
4878  !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4879  // C++ [temp.deduct.type]p17:
4880  // If, in the declaration of a function template with a non-type
4881  // template-parameter, the non-type template-parameter is used
4882  // in an expression in the function parameter-list and, if the
4883  // corresponding template-argument is deduced, the
4884  // template-argument type shall match the type of the
4885  // template-parameter exactly, except that a template-argument
4886  // deduced from an array bound may be of any integral type.
4887  Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4888  << Arg->getType().getUnqualifiedType()
4889  << ParamType.getUnqualifiedType();
4890  Diag(Param->getLocation(), diag::note_template_param_here);
4891  return ExprError();
4892  }
4893 
4894  if (getLangOpts().CPlusPlus1z) {
4895  // FIXME: We can do some limited checking for a value-dependent but not
4896  // type-dependent argument.
4897  if (Arg->isValueDependent()) {
4898  Converted = TemplateArgument(Arg);
4899  return Arg;
4900  }
4901 
4902  // C++1z [temp.arg.nontype]p1:
4903  // A template-argument for a non-type template parameter shall be
4904  // a converted constant expression of the type of the template-parameter.
4905  APValue Value;
4907  Arg, ParamType, Value, CCEK_TemplateArg);
4908  if (ArgResult.isInvalid())
4909  return ExprError();
4910 
4911  QualType CanonParamType = Context.getCanonicalType(ParamType);
4912 
4913  // Convert the APValue to a TemplateArgument.
4914  switch (Value.getKind()) {
4916  assert(ParamType->isNullPtrType());
4917  Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4918  break;
4919  case APValue::Int:
4920  assert(ParamType->isIntegralOrEnumerationType());
4921  Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4922  break;
4923  case APValue::MemberPointer: {
4924  assert(ParamType->isMemberPointerType());
4925 
4926  // FIXME: We need TemplateArgument representation and mangling for these.
4927  if (!Value.getMemberPointerPath().empty()) {
4928  Diag(Arg->getLocStart(),
4929  diag::err_template_arg_member_ptr_base_derived_not_supported)
4930  << Value.getMemberPointerDecl() << ParamType
4931  << Arg->getSourceRange();
4932  return ExprError();
4933  }
4934 
4935  auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4936  Converted = VD ? TemplateArgument(VD, CanonParamType)
4937  : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4938  break;
4939  }
4940  case APValue::LValue: {
4941  // For a non-type template-parameter of pointer or reference type,
4942  // the value of the constant expression shall not refer to
4943  assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4944  ParamType->isNullPtrType());
4945  // -- a temporary object
4946  // -- a string literal
4947  // -- the result of a typeid expression, or
4948  // -- a predefind __func__ variable
4949  if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4950  if (isa<CXXUuidofExpr>(E)) {
4951  Converted = TemplateArgument(const_cast<Expr*>(E));
4952  break;
4953  }
4954  Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4955  << Arg->getSourceRange();
4956  return ExprError();
4957  }
4958  auto *VD = const_cast<ValueDecl *>(
4959  Value.getLValueBase().dyn_cast<const ValueDecl *>());
4960  // -- a subobject
4961  if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4962  VD && VD->getType()->isArrayType() &&
4963  Value.getLValuePath()[0].ArrayIndex == 0 &&
4964  !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4965  // Per defect report (no number yet):
4966  // ... other than a pointer to the first element of a complete array
4967  // object.
4968  } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4969  Value.isLValueOnePastTheEnd()) {
4970  Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4971  << Value.getAsString(Context, ParamType);
4972  return ExprError();
4973  }
4974  assert((VD || !ParamType->isReferenceType()) &&
4975  "null reference should not be a constant expression");
4976  assert((!VD || !ParamType->isNullPtrType()) &&
4977  "non-null value of type nullptr_t?");
4978  Converted = VD ? TemplateArgument(VD, CanonParamType)
4979  : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4980  break;
4981  }
4983  return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4984  case APValue::Float:
4985  case APValue::ComplexInt:
4986  case APValue::ComplexFloat:
4987  case APValue::Vector:
4988  case APValue::Array:
4989  case APValue::Struct:
4990  case APValue::Union:
4991  llvm_unreachable("invalid kind for template argument");
4992  }
4993 
4994  return ArgResult.get();
4995  }
4996 
4997  // C++ [temp.arg.nontype]p5:
4998  // The following conversions are performed on each expression used
4999  // as a non-type template-argument. If a non-type
5000  // template-argument cannot be converted to the type of the
5001  // corresponding template-parameter then the program is
5002  // ill-formed.
5003  if (ParamType->isIntegralOrEnumerationType()) {
5004  // C++11:
5005  // -- for a non-type template-parameter of integral or
5006  // enumeration type, conversions permitted in a converted
5007  // constant expression are applied.
5008  //
5009  // C++98:
5010  // -- for a non-type template-parameter of integral or
5011  // enumeration type, integral promotions (4.5) and integral
5012  // conversions (4.7) are applied.
5013 
5014  if (getLangOpts().CPlusPlus11) {
5015  // We can't check arbitrary value-dependent arguments.
5016  // FIXME: If there's no viable conversion to the template parameter type,
5017  // we should be able to diagnose that prior to instantiation.
5018  if (Arg->isValueDependent()) {
5019  Converted = TemplateArgument(Arg);
5020  return Arg;
5021  }
5022 
5023  // C++ [temp.arg.nontype]p1:
5024  // A template-argument for a non-type, non-template template-parameter
5025  // shall be one of:
5026  //
5027  // -- for a non-type template-parameter of integral or enumeration
5028  // type, a converted constant expression of the type of the
5029  // template-parameter; or
5030  llvm::APSInt Value;
5031  ExprResult ArgResult =
5032  CheckConvertedConstantExpression(Arg, ParamType, Value,
5033  CCEK_TemplateArg);
5034  if (ArgResult.isInvalid())
5035  return ExprError();
5036 
5037  // Widen the argument value to sizeof(parameter type). This is almost
5038  // always a no-op, except when the parameter type is bool. In
5039  // that case, this may extend the argument from 1 bit to 8 bits.
5040  QualType IntegerType = ParamType;
5041  if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5042  IntegerType = Enum->getDecl()->getIntegerType();
5043  Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5044 
5045  Converted = TemplateArgument(Context, Value,
5046  Context.getCanonicalType(ParamType));
5047  return ArgResult;
5048  }
5049 
5050  ExprResult ArgResult = DefaultLvalueConversion(Arg);
5051  if (ArgResult.isInvalid())
5052  return ExprError();
5053  Arg = ArgResult.get();
5054 
5055  QualType ArgType = Arg->getType();
5056 
5057  // C++ [temp.arg.nontype]p1:
5058  // A template-argument for a non-type, non-template
5059  // template-parameter shall be one of:
5060  //
5061  // -- an integral constant-expression of integral or enumeration
5062  // type; or
5063  // -- the name of a non-type template-parameter; or
5064  SourceLocation NonConstantLoc;
5065  llvm::APSInt Value;
5066  if (!ArgType->isIntegralOrEnumerationType()) {
5067  Diag(Arg->getLocStart(),
5068  diag::err_template_arg_not_integral_or_enumeral)
5069  << ArgType << Arg->getSourceRange();
5070  Diag(Param->getLocation(), diag::note_template_param_here);
5071  return ExprError();
5072  } else if (!Arg->isValueDependent()) {
5073  class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5074  QualType T;
5075 
5076  public:
5077  TmplArgICEDiagnoser(QualType T) : T(T) { }
5078 
5079  void diagnoseNotICE(Sema &S, SourceLocation Loc,
5080  SourceRange SR) override {
5081  S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5082  }
5083  } Diagnoser(ArgType);
5084 
5085  Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5086  false).get();
5087  if (!Arg)
5088  return ExprError();
5089  }
5090 
5091  // From here on out, all we care about is the unqualified form
5092  // of the argument type.
5093  ArgType = ArgType.getUnqualifiedType();
5094 
5095  // Try to convert the argument to the parameter's type.
5096  if (Context.hasSameType(ParamType, ArgType)) {
5097  // Okay: no conversion necessary
5098  } else if (ParamType->isBooleanType()) {
5099  // This is an integral-to-boolean conversion.
5100  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5101  } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5102  !ParamType->isEnumeralType()) {
5103  // This is an integral promotion or conversion.
5104  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5105  } else {
5106  // We can't perform this conversion.
5107  Diag(Arg->getLocStart(),
5108  diag::err_template_arg_not_convertible)
5109  << Arg->getType() << ParamType << Arg->getSourceRange();
5110  Diag(Param->getLocation(), diag::note_template_param_here);
5111  return ExprError();
5112  }
5113 
5114  // Add the value of this argument to the list of converted
5115  // arguments. We use the bitwidth and signedness of the template
5116  // parameter.
5117  if (Arg->isValueDependent()) {
5118  // The argument is value-dependent. Create a new
5119  // TemplateArgument with the converted expression.
5120  Converted = TemplateArgument(Arg);
5121  return Arg;
5122  }
5123 
5124  QualType IntegerType = Context.getCanonicalType(ParamType);
5125  if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5126  IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5127 
5128  if (ParamType->isBooleanType()) {
5129  // Value must be zero or one.
5130  Value = Value != 0;
5131  unsigned AllowedBits = Context.getTypeSize(IntegerType);
5132  if (Value.getBitWidth() != AllowedBits)
5133  Value = Value.extOrTrunc(AllowedBits);
5134  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5135  } else {
5136  llvm::APSInt OldValue = Value;
5137 
5138  // Coerce the template argument's value to the value it will have
5139  // based on the template parameter's type.
5140  unsigned AllowedBits = Context.getTypeSize(IntegerType);
5141  if (Value.getBitWidth() != AllowedBits)
5142  Value = Value.extOrTrunc(AllowedBits);
5143  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5144 
5145  // Complain if an unsigned parameter received a negative value.
5146  if (IntegerType->isUnsignedIntegerOrEnumerationType()
5147  && (OldValue.isSigned() && OldValue.isNegative())) {
5148  Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5149  << OldValue.toString(10) << Value.toString(10) << Param->getType()
5150  << Arg->getSourceRange();
5151  Diag(Param->getLocation(), diag::note_template_param_here);
5152  }
5153 
5154  // Complain if we overflowed the template parameter's type.
5155  unsigned RequiredBits;
5156  if (IntegerType->isUnsignedIntegerOrEnumerationType())
5157  RequiredBits = OldValue.getActiveBits();
5158  else if (OldValue.isUnsigned())
5159  RequiredBits = OldValue.getActiveBits() + 1;
5160  else
5161  RequiredBits = OldValue.getMinSignedBits();
5162  if (RequiredBits > AllowedBits) {
5163  Diag(Arg->getLocStart(),
5164  diag::warn_template_arg_too_large)
5165  << OldValue.toString(10) << Value.toString(10) << Param->getType()
5166  << Arg->getSourceRange();
5167  Diag(Param->getLocation(), diag::note_template_param_here);
5168  }
5169  }
5170 
5171  Converted = TemplateArgument(Context, Value,
5172  ParamType->isEnumeralType()
5173  ? Context.getCanonicalType(ParamType)
5174  : IntegerType);
5175  return Arg;
5176  }
5177 
5178  QualType ArgType = Arg->getType();
5179  DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5180 
5181  // Handle pointer-to-function, reference-to-function, and
5182  // pointer-to-member-function all in (roughly) the same way.
5183  if (// -- For a non-type template-parameter of type pointer to
5184  // function, only the function-to-pointer conversion (4.3) is
5185  // applied. If the template-argument represents a set of
5186  // overloaded functions (or a pointer to such), the matching
5187  // function is selected from the set (13.4).
5188  (ParamType->isPointerType() &&
5189  ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5190  // -- For a non-type template-parameter of type reference to
5191  // function, no conversions apply. If the template-argument
5192  // represents a set of overloaded functions, the matching
5193  // function is selected from the set (13.4).
5194  (ParamType->isReferenceType() &&
5195  ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5196  // -- For a non-type template-parameter of type pointer to
5197  // member function, no conversions apply. If the
5198  // template-argument represents a set of overloaded member
5199  // functions, the matching member function is selected from
5200  // the set (13.4).
5201  (ParamType->isMemberPointerType() &&
5202  ParamType->getAs<MemberPointerType>()->getPointeeType()
5203  ->isFunctionType())) {
5204 
5205  if (Arg->getType() == Context.OverloadTy) {
5206  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5207  true,
5208  FoundResult)) {
5209  if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5210  return ExprError();
5211 
5212  Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5213  ArgType = Arg->getType();
5214  } else
5215  return ExprError();
5216  }
5217 
5218  if (!ParamType->isMemberPointerType()) {
5220  ParamType,
5221  Arg, Converted))
5222  return ExprError();
5223  return Arg;
5224  }
5225 
5226  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5227  Converted))
5228  return ExprError();
5229  return Arg;
5230  }
5231 
5232  if (ParamType->isPointerType()) {
5233  // -- for a non-type template-parameter of type pointer to
5234  // object, qualification conversions (4.4) and the
5235  // array-to-pointer conversion (4.2) are applied.
5236  // C++0x also allows a value of std::nullptr_t.
5237  assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5238  "Only object pointers allowed here");
5239 
5241  ParamType,
5242  Arg, Converted))
5243  return ExprError();
5244  return Arg;
5245  }
5246 
5247  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5248  // -- For a non-type template-parameter of type reference to
5249  // object, no conversions apply. The type referred to by the
5250  // reference may be more cv-qualified than the (otherwise
5251  // identical) type of the template-argument. The
5252  // template-parameter is bound directly to the
5253  // template-argument, which must be an lvalue.
5254  assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5255  "Only object references allowed here");
5256 
5257  if (Arg->getType() == Context.OverloadTy) {
5258  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5259  ParamRefType->getPointeeType(),
5260  true,
5261  FoundResult)) {
5262  if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5263  return ExprError();
5264 
5265  Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5266  ArgType = Arg->getType();
5267  } else
5268  return ExprError();
5269  }
5270 
5272  ParamType,
5273  Arg, Converted))
5274  return ExprError();
5275  return Arg;
5276  }
5277 
5278  // Deal with parameters of type std::nullptr_t.
5279  if (ParamType->isNullPtrType()) {
5280  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5281  Converted = TemplateArgument(Arg);
5282  return Arg;
5283  }
5284 
5285  switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5286  case NPV_NotNullPointer:
5287  Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5288  << Arg->getType() << ParamType;
5289  Diag(Param->getLocation(), diag::note_template_param_here);
5290  return ExprError();
5291 
5292  case NPV_Error:
5293  return ExprError();
5294 
5295  case NPV_NullPointer:
5296  Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5297  Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5298  /*isNullPtr*/true);
5299  return Arg;
5300  }
5301  }
5302 
5303  // -- For a non-type template-parameter of type pointer to data
5304  // member, qualification conversions (4.4) are applied.
5305  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5306 
5307  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5308  Converted))
5309  return ExprError();
5310  return Arg;
5311 }
5312 
5313 /// \brief Check a template argument against its corresponding
5314 /// template template parameter.
5315 ///
5316 /// This routine implements the semantics of C++ [temp.arg.template].
5317 /// It returns true if an error occurred, and false otherwise.
5319  TemplateArgumentLoc &Arg,
5320  unsigned ArgumentPackIndex) {
5322  TemplateDecl *Template = Name.getAsTemplateDecl();
5323  if (!Template) {
5324  // Any dependent template name is fine.
5325  assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5326  return false;
5327  }
5328 
5329  // C++0x [temp.arg.template]p1:
5330  // A template-argument for a template template-parameter shall be
5331  // the name of a class template or an alias template, expressed as an
5332  // id-expression. When the template-argument names a class template, only
5333  // primary class templates are considered when matching the
5334  // template template argument with the corresponding parameter;
5335  // partial specializations are not considered even if their
5336  // parameter lists match that of the template template parameter.
5337  //
5338  // Note that we also allow template template parameters here, which
5339  // will happen when we are dealing with, e.g., class template
5340  // partial specializations.
5341  if (!isa<ClassTemplateDecl>(Template) &&
5342  !isa<TemplateTemplateParmDecl>(Template) &&
5343  !isa<TypeAliasTemplateDecl>(Template)) {
5344  assert(isa<FunctionTemplateDecl>(Template) &&
5345  "Only function templates are possible here");
5346  Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5347  Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5348  << Template;
5349  }
5350 
5351  TemplateParameterList *Params = Param->getTemplateParameters();
5352  if (Param->isExpandedParameterPack())
5353  Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5354 
5355  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5356  Params,
5357  true,
5358  TPL_TemplateTemplateArgumentMatch,
5359  Arg.getLocation());
5360 }
5361 
5362 /// \brief Given a non-type template argument that refers to a
5363 /// declaration and the type of its corresponding non-type template
5364 /// parameter, produce an expression that properly refers to that
5365 /// declaration.
5366 ExprResult
5368  QualType ParamType,
5369  SourceLocation Loc) {
5370  // C++ [temp.param]p8:
5371  //
5372  // A non-type template-parameter of type "array of T" or
5373  // "function returning T" is adjusted to be of type "pointer to
5374  // T" or "pointer to function returning T", respectively.
5375  if (ParamType->isArrayType())
5376  ParamType = Context.getArrayDecayedType(ParamType);
5377  else if (ParamType->isFunctionType())
5378  ParamType = Context.getPointerType(ParamType);
5379 
5380  // For a NULL non-type template argument, return nullptr casted to the
5381  // parameter's type.
5382  if (Arg.getKind() == TemplateArgument::NullPtr) {
5383  return ImpCastExprToType(
5385  ParamType,
5386  ParamType->getAs<MemberPointerType>()
5388  : CK_NullToPointer);
5389  }
5390  assert(Arg.getKind() == TemplateArgument::Declaration &&
5391  "Only declaration template arguments permitted here");
5392 
5393  ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5394 
5395  if (VD->getDeclContext()->isRecord() &&
5396  (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5397  isa<IndirectFieldDecl>(VD))) {
5398  // If the value is a class member, we might have a pointer-to-member.
5399  // Determine whether the non-type template template parameter is of
5400  // pointer-to-member type. If so, we need to build an appropriate
5401  // expression for a pointer-to-member, since a "normal" DeclRefExpr
5402  // would refer to the member itself.
5403  if (ParamType->isMemberPointerType()) {
5404  QualType ClassType
5405  = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5406  NestedNameSpecifier *Qualifier
5407  = NestedNameSpecifier::Create(Context, nullptr, false,
5408  ClassType.getTypePtr());
5409  CXXScopeSpec SS;
5410  SS.MakeTrivial(Context, Qualifier, Loc);
5411 
5412  // The actual value-ness of this is unimportant, but for
5413  // internal consistency's sake, references to instance methods
5414  // are r-values.
5415  ExprValueKind VK = VK_LValue;
5416  if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5417  VK = VK_RValue;
5418 
5419  ExprResult RefExpr = BuildDeclRefExpr(VD,
5420  VD->getType().getNonReferenceType(),
5421  VK,
5422  Loc,
5423  &SS);
5424  if (RefExpr.isInvalid())
5425  return ExprError();
5426 
5427  RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5428 
5429  // We might need to perform a trailing qualification conversion, since
5430  // the element type on the parameter could be more qualified than the
5431  // element type in the expression we constructed.
5432  bool ObjCLifetimeConversion;
5433  if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5434  ParamType.getUnqualifiedType(), false,
5435  ObjCLifetimeConversion))
5436  RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5437 
5438  assert(!RefExpr.isInvalid() &&
5439  Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5440  ParamType.getUnqualifiedType()));
5441  return RefExpr;
5442  }
5443  }
5444 
5445  QualType T = VD->getType().getNonReferenceType();
5446 
5447  if (ParamType->isPointerType()) {
5448  // When the non-type template parameter is a pointer, take the
5449  // address of the declaration.
5450  ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5451  if (RefExpr.isInvalid())
5452  return ExprError();
5453 
5454  if (T->isFunctionType() || T->isArrayType()) {
5455  // Decay functions and arrays.
5456  RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5457  if (RefExpr.isInvalid())
5458  return ExprError();
5459 
5460  return RefExpr;
5461  }
5462 
5463  // Take the address of everything else
5464  return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5465  }
5466 
5467  ExprValueKind VK = VK_RValue;
5468 
5469  // If the non-type template parameter has reference type, qualify the
5470  // resulting declaration reference with the extra qualifiers on the
5471  // type that the reference refers to.
5472  if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5473  VK = VK_LValue;
5474  T = Context.getQualifiedType(T,
5475  TargetRef->getPointeeType().getQualifiers());
5476  } else if (isa<FunctionDecl>(VD)) {
5477  // References to functions are always lvalues.
5478  VK = VK_LValue;
5479  }
5480 
5481  return BuildDeclRefExpr(VD, T, VK, Loc);
5482 }
5483 
5484 /// \brief Construct a new expression that refers to the given
5485 /// integral template argument with the given source-location
5486 /// information.
5487 ///
5488 /// This routine takes care of the mapping from an integral template
5489 /// argument (which may have any integral type) to the appropriate
5490 /// literal value.
5491 ExprResult
5493  SourceLocation Loc) {
5494  assert(Arg.getKind() == TemplateArgument::Integral &&
5495  "Operation is only valid for integral template arguments");
5496  QualType OrigT = Arg.getIntegralType();
5497 
5498  // If this is an enum type that we're instantiating, we need to use an integer
5499  // type the same size as the enumerator. We don't want to build an
5500  // IntegerLiteral with enum type. The integer type of an enum type can be of
5501  // any integral type with C++11 enum classes, make sure we create the right
5502  // type of literal for it.
5503  QualType T = OrigT;
5504  if (const EnumType *ET = OrigT->getAs<EnumType>())
5505  T = ET->getDecl()->getIntegerType();
5506 
5507  Expr *E;
5508  if (T->isAnyCharacterType()) {
5509  // This does not need to handle u8 character literals because those are
5510  // of type char, and so can also be covered by an ASCII character literal.
5512  if (T->isWideCharType())
5513  Kind = CharacterLiteral::Wide;
5514  else if (T->isChar16Type())
5515  Kind = CharacterLiteral::UTF16;
5516  else if (T->isChar32Type())
5517  Kind = CharacterLiteral::UTF32;
5518  else
5519  Kind = CharacterLiteral::Ascii;
5520 
5521  E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5522  Kind, T, Loc);
5523  } else if (T->isBooleanType()) {
5524  E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5525  T, Loc);
5526  } else if (T->isNullPtrType()) {
5528  } else {
5529  E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5530  }
5531 
5532  if (OrigT->isEnumeralType()) {
5533  // FIXME: This is a hack. We need a better way to handle substituted
5534  // non-type template parameters.
5536  nullptr,
5537  Context.getTrivialTypeSourceInfo(OrigT, Loc),
5538  Loc, Loc);
5539  }
5540 
5541  return E;
5542 }
5543 
5544 /// \brief Match two template parameters within template parameter lists.
5546  bool Complain,
5548  SourceLocation TemplateArgLoc) {
5549  // Check the actual kind (type, non-type, template).
5550  if (Old->getKind() != New->getKind()) {
5551  if (Complain) {
5552  unsigned NextDiag = diag::err_template_param_different_kind;
5553  if (TemplateArgLoc.isValid()) {
5554  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5555  NextDiag = diag::note_template_param_different_kind;
5556  }
5557  S.Diag(New->getLocation(), NextDiag)
5558  << (Kind != Sema::TPL_TemplateMatch);
5559  S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5560  << (Kind != Sema::TPL_TemplateMatch);
5561  }
5562 
5563  return false;
5564  }
5565 
5566  // Check that both are parameter packs are neither are parameter packs.
5567  // However, if we are matching a template template argument to a
5568  // template template parameter, the template template parameter can have
5569  // a parameter pack where the template template argument does not.
5570  if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5572  Old->isTemplateParameterPack())) {
5573  if (Complain) {
5574  unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5575  if (TemplateArgLoc.isValid()) {
5576  S.Diag(TemplateArgLoc,
5577  diag::err_template_arg_template_params_mismatch);
5578  NextDiag = diag::note_template_parameter_pack_non_pack;
5579  }
5580 
5581  unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5582  : isa<NonTypeTemplateParmDecl>(New)? 1
5583  : 2;
5584  S.Diag(New->getLocation(), NextDiag)
5585  << ParamKind << New->isParameterPack();
5586  S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5587  << ParamKind << Old->isParameterPack();
5588  }
5589 
5590  return false;
5591  }
5592 
5593  // For non-type template parameters, check the type of the parameter.
5594  if (NonTypeTemplateParmDecl *OldNTTP
5595  = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5596  NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5597 
5598  // If we are matching a template template argument to a template
5599  // template parameter and one of the non-type template parameter types
5600  // is dependent, then we must wait until template instantiation time
5601  // to actually compare the arguments.
5603  (OldNTTP->getType()->isDependentType() ||
5604  NewNTTP->getType()->isDependentType()))
5605  return true;
5606 
5607  if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5608  if (Complain) {
5609  unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5610  if (TemplateArgLoc.isValid()) {
5611  S.Diag(TemplateArgLoc,
5612  diag::err_template_arg_template_params_mismatch);
5613  NextDiag = diag::note_template_nontype_parm_different_type;
5614  }
5615  S.Diag(NewNTTP->getLocation(), NextDiag)
5616  << NewNTTP->getType()
5617  << (Kind != Sema::TPL_TemplateMatch);
5618  S.Diag(OldNTTP->getLocation(),
5619  diag::note_template_nontype_parm_prev_declaration)
5620  << OldNTTP->getType();
5621  }
5622 
5623  return false;
5624  }
5625 
5626  return true;
5627  }
5628 
5629  // For template template parameters, check the template parameter types.
5630  // The template parameter lists of template template
5631  // parameters must agree.
5632  if (TemplateTemplateParmDecl *OldTTP
5633  = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5634  TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5636  OldTTP->getTemplateParameters(),
5637  Complain,
5638  (Kind == Sema::TPL_TemplateMatch
5640  : Kind),
5641  TemplateArgLoc);
5642  }
5643 
5644  return true;
5645 }
5646 
5647 /// \brief Diagnose a known arity mismatch when comparing template argument
5648 /// lists.
5649 static
5651  TemplateParameterList *New,
5652  TemplateParameterList *Old,
5654  SourceLocation TemplateArgLoc) {
5655  unsigned NextDiag = diag::err_template_param_list_different_arity;
5656  if (TemplateArgLoc.isValid()) {
5657  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5658  NextDiag = diag::note_template_param_list_different_arity;
5659  }
5660  S.Diag(New->getTemplateLoc(), NextDiag)
5661  << (New->size() > Old->size())
5662  << (Kind != Sema::TPL_TemplateMatch)
5663  << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5664  S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5665  << (Kind != Sema::TPL_TemplateMatch)
5666  << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5667 }
5668 
5669 /// \brief Determine whether the given template parameter lists are
5670 /// equivalent.
5671 ///
5672 /// \param New The new template parameter list, typically written in the
5673 /// source code as part of a new template declaration.
5674 ///
5675 /// \param Old The old template parameter list, typically found via
5676 /// name lookup of the template declared with this template parameter
5677 /// list.
5678 ///
5679 /// \param Complain If true, this routine will produce a diagnostic if
5680 /// the template parameter lists are not equivalent.
5681 ///
5682 /// \param Kind describes how we are to match the template parameter lists.
5683 ///
5684 /// \param TemplateArgLoc If this source location is valid, then we
5685 /// are actually checking the template parameter list of a template
5686 /// argument (New) against the template parameter list of its
5687 /// corresponding template template parameter (Old). We produce
5688 /// slightly different diagnostics in this scenario.
5689 ///
5690 /// \returns True if the template parameter lists are equal, false
5691 /// otherwise.
5692 bool
5694  TemplateParameterList *Old,
5695  bool Complain,
5697  SourceLocation TemplateArgLoc) {
5698  if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5699  if (Complain)
5700  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5701  TemplateArgLoc);
5702 
5703  return false;
5704  }
5705 
5706  // C++0x [temp.arg.template]p3:
5707  // A template-argument matches a template template-parameter (call it P)
5708  // when each of the template parameters in the template-parameter-list of
5709  // the template-argument's corresponding class template or alias template
5710  // (call it A) matches the corresponding template parameter in the
5711  // template-parameter-list of P. [...]
5712  TemplateParameterList::iterator NewParm = New->begin();
5713  TemplateParameterList::iterator NewParmEnd = New->end();
5714  for (TemplateParameterList::iterator OldParm = Old->begin(),
5715  OldParmEnd = Old->end();
5716  OldParm != OldParmEnd; ++OldParm) {
5717  if (Kind != TPL_TemplateTemplateArgumentMatch ||
5718  !(*OldParm)->isTemplateParameterPack()) {
5719  if (NewParm == NewParmEnd) {
5720  if (Complain)
5721  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5722  TemplateArgLoc);
5723 
5724  return false;
5725  }
5726 
5727  if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5728  Kind, TemplateArgLoc))
5729  return false;
5730 
5731  ++NewParm;
5732  continue;
5733  }
5734 
5735  // C++0x [temp.arg.template]p3:
5736  // [...] When P's template- parameter-list contains a template parameter
5737  // pack (14.5.3), the template parameter pack will match zero or more
5738  // template parameters or template parameter packs in the
5739  // template-parameter-list of A with the same type and form as the
5740  // template parameter pack in P (ignoring whether those template
5741  // parameters are template parameter packs).
5742  for (; NewParm != NewParmEnd; ++NewParm) {
5743  if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5744  Kind, TemplateArgLoc))
5745  return false;
5746  }
5747  }
5748 
5749  // Make sure we exhausted all of the arguments.
5750  if (NewParm != NewParmEnd) {
5751  if (Complain)
5752  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5753  TemplateArgLoc);
5754 
5755  return false;
5756  }
5757 
5758  return true;
5759 }
5760 
5761 /// \brief Check whether a template can be declared within this scope.
5762 ///
5763 /// If the template declaration is valid in this scope, returns
5764 /// false. Otherwise, issues a diagnostic and returns true.
5765 bool
5767  if (!S)
5768  return false;
5769 
5770  // Find the nearest enclosing declaration scope.
5771  while ((S->getFlags() & Scope::DeclScope) == 0 ||
5772  (S->getFlags() & Scope::TemplateParamScope) != 0)
5773  S = S->getParent();
5774 
5775  // C++ [temp]p4:
5776  // A template [...] shall not have C linkage.
5777  DeclContext *Ctx = S->getEntity();
5778  if (Ctx && Ctx->isExternCContext())
5779  return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5780  << TemplateParams->getSourceRange();
5781 
5782  while (Ctx && isa<LinkageSpecDecl>(Ctx))
5783  Ctx = Ctx->getParent();
5784 
5785  // C++ [temp]p2:
5786  // A template-declaration can appear only as a namespace scope or
5787  // class scope declaration.
5788  if (Ctx) {
5789  if (Ctx->isFileContext())
5790  return false;
5791  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5792  // C++ [temp.mem]p2:
5793  // A local class shall not have member templates.
5794  if (RD->isLocalClass())
5795  return Diag(TemplateParams->getTemplateLoc(),
5796  diag::err_template_inside_local_class)
5797  << TemplateParams->getSourceRange();
5798  else
5799  return false;
5800  }
5801  }
5802 
5803  return Diag(TemplateParams->getTemplateLoc(),
5804  diag::err_template_outside_namespace_or_class_scope)
5805  << TemplateParams->getSourceRange();
5806 }
5807 
5808 /// \brief Determine what kind of template specialization the given declaration
5809 /// is.
5811  if (!D)
5812  return TSK_Undeclared;
5813 
5814  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5815  return Record->getTemplateSpecializationKind();
5816  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5817  return Function->getTemplateSpecializationKind();
5818  if (VarDecl *Var = dyn_cast<VarDecl>(D))
5819  return Var->getTemplateSpecializationKind();
5820 
5821  return TSK_Undeclared;
5822 }
5823 
5824 /// \brief Check whether a specialization is well-formed in the current
5825 /// context.
5826 ///
5827 /// This routine determines whether a template specialization can be declared
5828 /// in the current context (C++ [temp.expl.spec]p2).
5829 ///
5830 /// \param S the semantic analysis object for which this check is being
5831 /// performed.
5832 ///
5833 /// \param Specialized the entity being specialized or instantiated, which
5834 /// may be a kind of template (class template, function template, etc.) or
5835 /// a member of a class template (member function, static data member,
5836 /// member class).
5837 ///
5838 /// \param PrevDecl the previous declaration of this entity, if any.
5839 ///
5840 /// \param Loc the location of the explicit specialization or instantiation of
5841 /// this entity.
5842 ///
5843 /// \param IsPartialSpecialization whether this is a partial specialization of
5844 /// a class template.
5845 ///
5846 /// \returns true if there was an error that we cannot recover from, false
5847 /// otherwise.
5849  NamedDecl *Specialized,
5850  NamedDecl *PrevDecl,
5851  SourceLocation Loc,
5852  bool IsPartialSpecialization) {
5853  // Keep these "kind" numbers in sync with the %select statements in the
5854  // various diagnostics emitted by this routine.
5855  int EntityKind = 0;
5856  if (isa<ClassTemplateDecl>(Specialized))
5857  EntityKind = IsPartialSpecialization? 1 : 0;
5858  else if (isa<VarTemplateDecl>(Specialized))
5859  EntityKind = IsPartialSpecialization ? 3 : 2;
5860  else if (isa<FunctionTemplateDecl>(Specialized))
5861  EntityKind = 4;
5862  else if (isa<CXXMethodDecl>(Specialized))
5863  EntityKind = 5;
5864  else if (isa<VarDecl>(Specialized))
5865  EntityKind = 6;
5866  else if (isa<RecordDecl>(Specialized))
5867  EntityKind = 7;
5868  else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5869  EntityKind = 8;
5870  else {
5871  S.Diag(Loc, diag::err_template_spec_unknown_kind)
5872  << S.getLangOpts().CPlusPlus11;
5873  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5874  return true;
5875  }
5876 
5877  // C++ [temp.expl.spec]p2:
5878  // An explicit specialization shall be declared in the namespace
5879  // of which the template is a member, or, for member templates, in
5880  // the namespace of which the enclosing class or enclosing class
5881  // template is a member. An explicit specialization of a member
5882  // function, member class or static data member of a class
5883  // template shall be declared in the namespace of which the class
5884  // template is a member. Such a declaration may also be a
5885  // definition. If the declaration is not a definition, the
5886  // specialization may be defined later in the name- space in which
5887  // the explicit specialization was declared, or in a namespace
5888  // that encloses the one in which the explicit specialization was
5889  // declared.
5891  S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5892  << Specialized;
5893  return true;
5894  }
5895 
5896  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5897  if (S.getLangOpts().MicrosoftExt) {
5898  // Do not warn for class scope explicit specialization during
5899  // instantiation, warning was already emitted during pattern
5900  // semantic analysis.
5901  if (!S.ActiveTemplateInstantiations.size())
5902  S.Diag(Loc, diag::ext_function_specialization_in_class)
5903  << Specialized;
5904  } else {
5905  S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5906  << Specialized;
5907  return true;
5908  }
5909  }
5910 
5911  if (S.CurContext->isRecord() &&
5912  !S.CurContext->Equals(Specialized->getDeclContext())) {
5913  // Make sure that we're specializing in the right record context.
5914  // Otherwise, things can go horribly wrong.
5915  S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5916  << Specialized;
5917  return true;
5918  }
5919 
5920  // C++ [temp.class.spec]p6:
5921  // A class template partial specialization may be declared or redeclared
5922  // in any namespace scope in which its definition may be defined (14.5.1
5923  // and 14.5.2).
5924  DeclContext *SpecializedContext
5925  = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5927 
5928  // Make sure that this redeclaration (or definition) occurs in an enclosing
5929  // namespace.
5930  // Note that HandleDeclarator() performs this check for explicit
5931  // specializations of function templates, static data members, and member
5932  // functions, so we skip the check here for those kinds of entities.
5933  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5934  // Should we refactor that check, so that it occurs later?
5935  if (!DC->Encloses(SpecializedContext) &&
5936  !(isa<FunctionTemplateDecl>(Specialized) ||
5937  isa<FunctionDecl>(Specialized) ||
5938  isa<VarTemplateDecl>(Specialized) ||
5939  isa<VarDecl>(Specialized))) {
5940  if (isa<TranslationUnitDecl>(SpecializedContext))
5941  S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5942  << EntityKind << Specialized;
5943  else if (isa<NamespaceDecl>(SpecializedContext)) {
5944  int Diag = diag::err_template_spec_redecl_out_of_scope;
5945  if (S.getLangOpts().MicrosoftExt)
5946  Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5947  S.Diag(Loc, Diag) << EntityKind << Specialized
5948  << cast<NamedDecl>(SpecializedContext);
5949  } else
5950  llvm_unreachable("unexpected namespace context for specialization");
5951 
5952  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5953  } else if ((!PrevDecl ||
5955  getTemplateSpecializationKind(PrevDecl) ==
5957  // C++ [temp.exp.spec]p2:
5958  // An explicit specialization shall be declared in the namespace of which
5959  // the template is a member, or, for member templates, in the namespace
5960  // of which the enclosing class or enclosing class template is a member.
5961  // An explicit specialization of a member function, member class or
5962  // static data member of a class template shall be declared in the
5963  // namespace of which the class template is a member.
5964  //
5965  // C++11 [temp.expl.spec]p2:
5966  // An explicit specialization shall be declared in a namespace enclosing
5967  // the specialized template.
5968  // C++11 [temp.explicit]p3:
5969  // An explicit instantiation shall appear in an enclosing namespace of its
5970  // template.
5971  if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5972  bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5973  if (isa<TranslationUnitDecl>(SpecializedContext)) {
5974  assert(!IsCPlusPlus11Extension &&
5975  "DC encloses TU but isn't in enclosing namespace set");
5976  S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5977  << EntityKind << Specialized;
5978  } else if (isa<NamespaceDecl>(SpecializedContext)) {
5979  int Diag;
5980  if (!IsCPlusPlus11Extension)
5981  Diag = diag::err_template_spec_decl_out_of_scope;
5982  else if (!S.getLangOpts().CPlusPlus11)
5983  Diag = diag::ext_template_spec_decl_out_of_scope;
5984  else
5985  Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5986  S.Diag(Loc, Diag)
5987  << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5988  }
5989 
5990  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5991  }
5992  }
5993 
5994  return false;
5995 }
5996 
5998  if (!E->isInstantiationDependent())
5999  return SourceLocation();
6000  DependencyChecker Checker(Depth);
6001  Checker.TraverseStmt(E);
6002  if (Checker.Match && Checker.MatchLoc.isInvalid())
6003  return E->getSourceRange();
6004  return Checker.MatchLoc;
6005 }
6006 
6008  if (!TL.getType()->isDependentType())
6009  return SourceLocation();
6010  DependencyChecker Checker(Depth);
6011  Checker.TraverseTypeLoc(TL);
6012  if (Checker.Match && Checker.MatchLoc.isInvalid())
6013  return TL.getSourceRange();
6014  return Checker.MatchLoc;
6015 }
6016 
6017 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
6018 /// that checks non-type template partial specialization arguments.
6020  Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6021  const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
6022  for (unsigned I = 0; I != NumArgs; ++I) {
6023  if (Args[I].getKind() == TemplateArgument::Pack) {
6025  S, TemplateNameLoc, Param, Args[I].pack_begin(),
6026  Args[I].pack_size(), IsDefaultArgument))
6027  return true;
6028 
6029  continue;
6030  }
6031 
6032  if (Args[I].getKind() != TemplateArgument::Expression)
6033  continue;
6034 
6035  Expr *ArgExpr = Args[I].getAsExpr();
6036 
6037  // We can have a pack expansion of any of the bullets below.
6038  if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6039  ArgExpr = Expansion->getPattern();
6040 
6041  // Strip off any implicit casts we added as part of type checking.
6042  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6043  ArgExpr = ICE->getSubExpr();
6044 
6045  // C++ [temp.class.spec]p8:
6046  // A non-type argument is non-specialized if it is the name of a
6047  // non-type parameter. All other non-type arguments are
6048  // specialized.
6049  //
6050  // Below, we check the two conditions that only apply to
6051  // specialized non-type arguments, so skip any non-specialized
6052  // arguments.
6053  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
6054  if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
6055  continue;
6056 
6057  // C++ [temp.class.spec]p9:
6058  // Within the argument list of a class template partial
6059  // specialization, the following restrictions apply:
6060  // -- A partially specialized non-type argument expression
6061  // shall not involve a template parameter of the partial
6062  // specialization except when the argument expression is a
6063  // simple identifier.
6064  SourceRange ParamUseRange =
6065  findTemplateParameter(Param->getDepth(), ArgExpr);
6066  if (ParamUseRange.isValid()) {
6067  if (IsDefaultArgument) {
6068  S.Diag(TemplateNameLoc,
6069  diag::err_dependent_non_type_arg_in_partial_spec);
6070  S.Diag(ParamUseRange.getBegin(),
6071  diag::note_dependent_non_type_default_arg_in_partial_spec)
6072  << ParamUseRange;
6073  } else {
6074  S.Diag(ParamUseRange.getBegin(),
6075  diag::err_dependent_non_type_arg_in_partial_spec)
6076  << ParamUseRange;
6077  }
6078  return true;
6079  }
6080 
6081  // -- The type of a template parameter corresponding to a
6082  // specialized non-type argument shall not be dependent on a
6083  // parameter of the specialization.
6084  //
6085  // FIXME: We need to delay this check until instantiation in some cases:
6086  //
6087  // template<template<typename> class X> struct A {
6088  // template<typename T, X<T> N> struct B;
6089  // template<typename T> struct B<T, 0>;
6090  // };
6091  // template<typename> using X = int;
6092  // A<X>::B<int, 0> b;
6093  ParamUseRange = findTemplateParameter(
6094  Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6095  if (ParamUseRange.isValid()) {
6096  S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6097  diag::err_dependent_typed_non_type_arg_in_partial_spec)
6098  << Param->getType() << ParamUseRange;
6099  S.Diag(Param->getLocation(), diag::note_template_param_here)
6100  << (IsDefaultArgument ? ParamUseRange : SourceRange());
6101  return true;
6102  }
6103  }
6104 
6105  return false;
6106 }
6107 
6108 /// \brief Check the non-type template arguments of a class template
6109 /// partial specialization according to C++ [temp.class.spec]p9.
6110 ///
6111 /// \param TemplateNameLoc the location of the template name.
6112 /// \param TemplateParams the template parameters of the primary class
6113 /// template.
6114 /// \param NumExplicit the number of explicitly-specified template arguments.
6115 /// \param TemplateArgs the template arguments of the class template
6116 /// partial specialization.
6117 ///
6118 /// \returns \c true if there was an error, \c false otherwise.
6120  Sema &S, SourceLocation TemplateNameLoc,
6121  TemplateParameterList *TemplateParams, unsigned NumExplicit,
6122  SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6123  const TemplateArgument *ArgList = TemplateArgs.data();
6124 
6125  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6127  = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6128  if (!Param)
6129  continue;
6130 
6132  S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6133  return true;
6134  }
6135 
6136  return false;
6137 }
6138 
6139 DeclResult
6141  TagUseKind TUK,
6142  SourceLocation KWLoc,
6143  SourceLocation ModulePrivateLoc,
6144  TemplateIdAnnotation &TemplateId,
6147  TemplateParameterLists,
6148  SkipBodyInfo *SkipBody) {
6149  assert(TUK != TUK_Reference && "References are not specializations");
6150 
6151  CXXScopeSpec &SS = TemplateId.SS;
6152 
6153  // NOTE: KWLoc is the location of the tag keyword. This will instead
6154  // store the location of the outermost template keyword in the declaration.
6155  SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6156  ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6157  SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6158  SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6159  SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6160 
6161  // Find the class template we're specializing
6162  TemplateName Name = TemplateId.Template.get();
6163  ClassTemplateDecl *ClassTemplate
6164  = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6165 
6166  if (!ClassTemplate) {
6167  Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6168  << (Name.getAsTemplateDecl() &&
6169  isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6170  return true;
6171  }
6172 
6173  bool isExplicitSpecialization = false;
6174  bool isPartialSpecialization = false;
6175 
6176  // Check the validity of the template headers that introduce this
6177  // template.
6178  // FIXME: We probably shouldn't complain about these headers for
6179  // friend declarations.
6180  bool Invalid = false;
6181  TemplateParameterList *TemplateParams =
6182  MatchTemplateParametersToScopeSpecifier(
6183  KWLoc, TemplateNameLoc, SS, &TemplateId,
6184  TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6185  Invalid);
6186  if (Invalid)
6187  return true;
6188 
6189  if (TemplateParams && TemplateParams->size() > 0) {
6190  isPartialSpecialization = true;
6191 
6192  if (TUK == TUK_Friend) {
6193  Diag(KWLoc, diag::err_partial_specialization_friend)
6194  << SourceRange(LAngleLoc, RAngleLoc);
6195  return true;
6196  }
6197 
6198  // C++ [temp.class.spec]p10:
6199  // The template parameter list of a specialization shall not
6200  // contain default template argument values.
6201  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6202  Decl *Param = TemplateParams->getParam(I);
6203  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6204  if (TTP->hasDefaultArgument()) {
6205  Diag(TTP->getDefaultArgumentLoc(),
6206  diag::err_default_arg_in_partial_spec);
6207  TTP->removeDefaultArgument();
6208  }
6209  } else if (NonTypeTemplateParmDecl *NTTP
6210  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6211  if (Expr *DefArg = NTTP->getDefaultArgument()) {
6212  Diag(NTTP->getDefaultArgumentLoc(),
6213  diag::err_default_arg_in_partial_spec)
6214  << DefArg->getSourceRange();
6215  NTTP->removeDefaultArgument();
6216  }
6217  } else {
6218  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6219  if (TTP->hasDefaultArgument()) {
6221  diag::err_default_arg_in_partial_spec)
6222  << TTP->getDefaultArgument().getSourceRange();
6223  TTP->removeDefaultArgument();
6224  }
6225  }
6226  }
6227  } else if (TemplateParams) {
6228  if (TUK == TUK_Friend)
6229  Diag(KWLoc, diag::err_template_spec_friend)
6231  SourceRange(TemplateParams->getTemplateLoc(),
6232  TemplateParams->getRAngleLoc()))
6233  << SourceRange(LAngleLoc, RAngleLoc);
6234  else
6235  isExplicitSpecialization = true;
6236  } else {
6237  assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6238  }
6239 
6240  // Check that the specialization uses the same tag kind as the
6241  // original template.
6243  assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6244  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6245  Kind, TUK == TUK_Definition, KWLoc,
6246  ClassTemplate->getIdentifier())) {
6247  Diag(KWLoc, diag::err_use_with_wrong_tag)
6248  << ClassTemplate
6250  ClassTemplate->getTemplatedDecl()->getKindName());
6251  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6252  diag::note_previous_use);
6253  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6254  }
6255 
6256  // Translate the parser's template argument list in our AST format.
6257  TemplateArgumentListInfo TemplateArgs =
6258  makeTemplateArgumentListInfo(*this, TemplateId);
6259 
6260  // Check for unexpanded parameter packs in any of the template arguments.
6261  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6262  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6263  UPPC_PartialSpecialization))
6264  return true;
6265 
6266  // Check that the template argument list is well-formed for this
6267  // template.
6269  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6270  TemplateArgs, false, Converted))
6271  return true;
6272 
6273  // Find the class template (partial) specialization declaration that
6274  // corresponds to these arguments.
6275  if (isPartialSpecialization) {
6277  *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6278  TemplateArgs.size(), Converted))
6279  return true;
6280 
6281  bool InstantiationDependent;
6282  if (!Name.isDependent() &&
6284  TemplateArgs.getArgumentArray(),
6285  TemplateArgs.size(),
6286  InstantiationDependent)) {
6287  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6288  << ClassTemplate->getDeclName();
6289  isPartialSpecialization = false;
6290  }
6291  }
6292 
6293  void *InsertPos = nullptr;
6294  ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6295 
6296  if (isPartialSpecialization)
6297  // FIXME: Template parameter list matters, too
6298  PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6299  else
6300  PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6301 
6302  ClassTemplateSpecializationDecl *Specialization = nullptr;
6303 
6304  // Check whether we can declare a class template specialization in
6305  // the current scope.
6306  if (TUK != TUK_Friend &&
6307  CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6308  TemplateNameLoc,
6309  isPartialSpecialization))
6310  return true;
6311 
6312  // The canonical type
6313  QualType CanonType;
6314  if (isPartialSpecialization) {
6315  // Build the canonical type that describes the converted template
6316  // arguments of the class template partial specialization.
6317  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6318  CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6319  Converted.data(),
6320  Converted.size());
6321 
6322  if (Context.hasSameType(CanonType,
6323  ClassTemplate->getInjectedClassNameSpecialization())) {
6324  // C++ [temp.class.spec]p9b3:
6325  //
6326  // -- The argument list of the specialization shall not be identical
6327  // to the implicit argument list of the primary template.
6328  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6329  << /*class template*/0 << (TUK == TUK_Definition)
6330  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6331  return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6332  ClassTemplate->getIdentifier(),
6333  TemplateNameLoc,
6334  Attr,
6335  TemplateParams,
6336  AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6337  /*FriendLoc*/SourceLocation(),
6338  TemplateParameterLists.size() - 1,
6339  TemplateParameterLists.data());
6340  }
6341 
6342  // Create a new class template partial specialization declaration node.
6344  = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6347  ClassTemplate->getDeclContext(),
6348  KWLoc, TemplateNameLoc,
6349  TemplateParams,
6350  ClassTemplate,
6351  Converted.data(),
6352  Converted.size(),
6353  TemplateArgs,
6354  CanonType,
6355  PrevPartial);
6356  SetNestedNameSpecifier(Partial, SS);
6357  if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6358  Partial->setTemplateParameterListsInfo(
6359  Context, TemplateParameterLists.drop_back(1));
6360  }
6361 
6362  if (!PrevPartial)
6363  ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6364  Specialization = Partial;
6365 
6366  // If we are providing an explicit specialization of a member class
6367  // template specialization, make a note of that.
6368  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6369  PrevPartial->setMemberSpecialization();
6370 
6371  // Check that all of the template parameters of the class template
6372  // partial specialization are deducible from the template
6373  // arguments. If not, this class template partial specialization
6374  // will never be used.
6375  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6376  MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6377  TemplateParams->getDepth(),
6378  DeducibleParams);
6379 
6380  if (!DeducibleParams.all()) {
6381  unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6382  Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6383  << /*class template*/0 << (NumNonDeducible > 1)
6384  << SourceRange(TemplateNameLoc, RAngleLoc);
6385  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6386  if (!DeducibleParams[I]) {
6387  NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6388  if (Param->getDeclName())
6389  Diag(Param->getLocation(),
6390  diag::note_partial_spec_unused_parameter)
6391  << Param->getDeclName();
6392  else
6393  Diag(Param->getLocation(),
6394  diag::note_partial_spec_unused_parameter)
6395  << "(anonymous)";
6396  }
6397  }
6398  }
6399  } else {
6400  // Create a new class template specialization declaration node for
6401  // this explicit specialization or friend declaration.
6402  Specialization
6404  ClassTemplate->getDeclContext(),
6405  KWLoc, TemplateNameLoc,
6406  ClassTemplate,
6407  Converted.data(),
6408  Converted.size(),
6409  PrevDecl);
6410  SetNestedNameSpecifier(Specialization, SS);
6411  if (TemplateParameterLists.size() > 0) {
6412  Specialization->setTemplateParameterListsInfo(Context,
6413  TemplateParameterLists);
6414  }
6415 
6416  if (!PrevDecl)
6417  ClassTemplate->AddSpecialization(Specialization, InsertPos);
6418 
6419  if (CurContext->isDependentContext()) {
6420  // -fms-extensions permits specialization of nested classes without
6421  // fully specializing the outer class(es).
6422  assert(getLangOpts().MicrosoftExt &&
6423  "Only possible with -fms-extensions!");
6424  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6426  CanonTemplate, Converted.data(), Converted.size());
6427  } else {
6428  CanonType = Context.getTypeDeclType(Specialization);
6429  }
6430  }
6431 
6432  // C++ [temp.expl.spec]p6:
6433  // If a template, a member template or the member of a class template is
6434  // explicitly specialized then that specialization shall be declared
6435  // before the first use of that specialization that would cause an implicit
6436  // instantiation to take place, in every translation unit in which such a
6437  // use occurs; no diagnostic is required.
6438  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6439  bool Okay = false;
6440  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6441  // Is there any previous explicit specialization declaration?
6443  Okay = true;
6444  break;
6445  }
6446  }
6447 
6448  if (!Okay) {
6449  SourceRange Range(TemplateNameLoc, RAngleLoc);
6450  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6451  << Context.getTypeDeclType(Specialization) << Range;
6452 
6453  Diag(PrevDecl->getPointOfInstantiation(),
6454  diag::note_instantiation_required_here)
6455  << (PrevDecl->getTemplateSpecializationKind()
6457  return true;
6458  }
6459  }
6460 
6461  // If this is not a friend, note that this is an explicit specialization.
6462  if (TUK != TUK_Friend)
6464 
6465  // Check that this isn't a redefinition of this specialization.
6466  if (TUK == TUK_Definition) {
6467  RecordDecl *Def = Specialization->getDefinition();
6468  NamedDecl *Hidden = nullptr;
6469  if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6470  SkipBody->ShouldSkip = true;
6471  makeMergedDefinitionVisible(Hidden, KWLoc);
6472  // From here on out, treat this as just a redeclaration.
6473  TUK = TUK_Declaration;
6474  } else if (Def) {
6475  SourceRange Range(TemplateNameLoc, RAngleLoc);
6476  Diag(TemplateNameLoc, diag::err_redefinition)
6477  << Context.getTypeDeclType(Specialization) << Range;
6478  Diag(Def->getLocation(), diag::note_previous_definition);
6479  Specialization->setInvalidDecl();
6480  return true;
6481  }
6482  }
6483 
6484  if (Attr)
6485  ProcessDeclAttributeList(S, Specialization, Attr);
6486 
6487  // Add alignment attributes if necessary; these attributes are checked when
6488  // the ASTContext lays out the structure.
6489  if (TUK == TUK_Definition) {
6490  AddAlignmentAttributesForRecord(Specialization);
6491  AddMsStructLayoutForRecord(Specialization);
6492  }
6493 
6494  if (ModulePrivateLoc.isValid())
6495  Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6496  << (isPartialSpecialization? 1 : 0)
6497  << FixItHint::CreateRemoval(ModulePrivateLoc);
6498 
6499  // Build the fully-sugared type for this class template
6500  // specialization as the user wrote in the specialization
6501  // itself. This means that we'll pretty-print the type retrieved
6502  // from the specialization's declaration the way that the user
6503  // actually wrote the specialization, rather than formatting the
6504  // name based on the "canonical" representation used to store the
6505  // template arguments in the specialization.
6506  TypeSourceInfo *WrittenTy
6507  = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6508  TemplateArgs, CanonType);
6509  if (TUK != TUK_Friend) {
6510  Specialization->setTypeAsWritten(WrittenTy);
6511  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6512  }
6513 
6514  // C++ [temp.expl.spec]p9:
6515  // A template explicit specialization is in the scope of the
6516  // namespace in which the template was defined.
6517  //
6518  // We actually implement this paragraph where we set the semantic
6519  // context (in the creation of the ClassTemplateSpecializationDecl),
6520  // but we also maintain the lexical context where the actual
6521  // definition occurs.
6522  Specialization->setLexicalDeclContext(CurContext);
6523 
6524  // We may be starting the definition of this specialization.
6525  if (TUK == TUK_Definition)
6526  Specialization->startDefinition();
6527 
6528  if (TUK == TUK_Friend) {
6529  FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6530  TemplateNameLoc,
6531  WrittenTy,
6532  /*FIXME:*/KWLoc);
6533  Friend->setAccess(AS_public);
6534  CurContext->addDecl(Friend);
6535  } else {
6536  // Add the specialization into its lexical context, so that it can
6537  // be seen when iterating through the list of declarations in that
6538  // context. However, specializations are not found by name lookup.
6539  CurContext->addDecl(Specialization);
6540  }
6541  return Specialization;
6542 }
6543 
6545  MultiTemplateParamsArg TemplateParameterLists,
6546  Declarator &D) {
6547  Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6548  ActOnDocumentableDecl(NewDecl);
6549  return NewDecl;
6550 }
6551 
6552 /// \brief Strips various properties off an implicit instantiation
6553 /// that has just been explicitly specialized.
6555  D->dropAttr<DLLImportAttr>();
6556  D->dropAttr<DLLExportAttr>();
6557 
6558  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6559  FD->setInlineSpecified(false);
6560 }
6561 
6562 /// \brief Compute the diagnostic location for an explicit instantiation
6563 // declaration or definition.
6565  NamedDecl* D, SourceLocation PointOfInstantiation) {
6566  // Explicit instantiations following a specialization have no effect and
6567  // hence no PointOfInstantiation. In that case, walk decl backwards
6568  // until a valid name loc is found.
6569  SourceLocation PrevDiagLoc = PointOfInstantiation;
6570  for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6571  Prev = Prev->getPreviousDecl()) {
6572  PrevDiagLoc = Prev->getLocation();
6573  }
6574  assert(PrevDiagLoc.isValid() &&
6575  "Explicit instantiation without point of instantiation?");
6576  return PrevDiagLoc;
6577 }
6578 
6579 /// \brief Diagnose cases where we have an explicit template specialization
6580 /// before/after an explicit template instantiation, producing diagnostics
6581 /// for those cases where they are required and determining whether the
6582 /// new specialization/instantiation will have any effect.
6583 ///
6584 /// \param NewLoc the location of the new explicit specialization or
6585 /// instantiation.
6586 ///
6587 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6588 ///
6589 /// \param PrevDecl the previous declaration of the entity.
6590 ///
6591 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6592 ///
6593 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6594 /// declaration was instantiated (either implicitly or explicitly).
6595 ///
6596 /// \param HasNoEffect will be set to true to indicate that the new
6597 /// specialization or instantiation has no effect and should be ignored.
6598 ///
6599 /// \returns true if there was an error that should prevent the introduction of
6600 /// the new declaration into the AST, false otherwise.
6601 bool
6604  NamedDecl *PrevDecl,
6606  SourceLocation PrevPointOfInstantiation,
6607  bool &HasNoEffect) {
6608  HasNoEffect = false;
6609 
6610  switch (NewTSK) {
6611  case TSK_Undeclared:
6613  assert(
6614  (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6615  "previous declaration must be implicit!");
6616  return false;
6617 
6619  switch (PrevTSK) {
6620  case TSK_Undeclared:
6622  // Okay, we're just specializing something that is either already
6623  // explicitly specialized or has merely been mentioned without any
6624  // instantiation.
6625  return false;
6626 
6628  if (PrevPointOfInstantiation.isInvalid()) {
6629  // The declaration itself has not actually been instantiated, so it is
6630  // still okay to specialize it.
6631  StripImplicitInstantiation(PrevDecl);
6632  return false;
6633  }
6634  // Fall through
6635 
6638  assert((PrevTSK == TSK_ImplicitInstantiation ||
6639  PrevPointOfInstantiation.isValid()) &&
6640  "Explicit instantiation without point of instantiation?");
6641 
6642  // C++ [temp.expl.spec]p6:
6643  // If a template, a member template or the member of a class template
6644  // is explicitly specialized then that specialization shall be declared
6645  // before the first use of that specialization that would cause an
6646  // implicit instantiation to take place, in every translation unit in
6647  // which such a use occurs; no diagnostic is required.
6648  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6649  // Is there any previous explicit specialization declaration?
6651  return false;
6652  }
6653 
6654  Diag(NewLoc, diag::err_specialization_after_instantiation)
6655  << PrevDecl;
6656  Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6657  << (PrevTSK != TSK_ImplicitInstantiation);
6658 
6659  return true;
6660  }
6661 
6663  switch (PrevTSK) {
6665  // This explicit instantiation declaration is redundant (that's okay).
6666  HasNoEffect = true;
6667  return false;
6668 
6669  case TSK_Undeclared:
6671  // We're explicitly instantiating something that may have already been
6672  // implicitly instantiated; that's fine.
6673  return false;
6674 
6676  // C++0x [temp.explicit]p4:
6677  // For a given set of template parameters, if an explicit instantiation
6678  // of a template appears after a declaration of an explicit
6679  // specialization for that template, the explicit instantiation has no
6680  // effect.
6681  HasNoEffect = true;
6682  return false;
6683 
6685  // C++0x [temp.explicit]p10:
6686  // If an entity is the subject of both an explicit instantiation
6687  // declaration and an explicit instantiation definition in the same
6688  // translation unit, the definition shall follow the declaration.
6689  Diag(NewLoc,
6690  diag::err_explicit_instantiation_declaration_after_definition);
6691 
6692  // Explicit instantiations following a specialization have no effect and
6693  // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6694  // until a valid name loc is found.
6695  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6696  diag::note_explicit_instantiation_definition_here);
6697  HasNoEffect = true;
6698  return false;
6699  }
6700 
6702  switch (PrevTSK) {
6703  case TSK_Undeclared:
6705  // We're explicitly instantiating something that may have already been
6706  // implicitly instantiated; that's fine.
6707  return false;
6708 
6710  // C++ DR 259, C++0x [temp.explicit]p4:
6711  // For a given set of template parameters, if an explicit
6712  // instantiation of a template appears after a declaration of
6713  // an explicit specialization for that template, the explicit
6714  // instantiation has no effect.
6715  //
6716  // In C++98/03 mode, we only give an extension warning here, because it
6717  // is not harmful to try to explicitly instantiate something that
6718  // has been explicitly specialized.
6719  Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6720  diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6721  diag::ext_explicit_instantiation_after_specialization)
6722  << PrevDecl;
6723  Diag(PrevDecl->getLocation(),
6724  diag::note_previous_template_specialization);
6725  HasNoEffect = true;
6726  return false;
6727 
6729  // We're explicity instantiating a definition for something for which we
6730  // were previously asked to suppress instantiations. That's fine.
6731 
6732  // C++0x [temp.explicit]p4:
6733  // For a given set of template parameters, if an explicit instantiation
6734  // of a template appears after a declaration of an explicit
6735  // specialization for that template, the explicit instantiation has no
6736  // effect.
6737  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6738  // Is there any previous explicit specialization declaration?
6740  HasNoEffect = true;
6741  break;
6742  }
6743  }
6744 
6745  return false;
6746 
6748  // C++0x [temp.spec]p5:
6749  // For a given template and a given set of template-arguments,
6750  // - an explicit instantiation definition shall appear at most once
6751  // in a program,
6752 
6753  // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6754  Diag(NewLoc, (getLangOpts().MSVCCompat)
6755  ? diag::ext_explicit_instantiation_duplicate
6756  : diag::err_explicit_instantiation_duplicate)
6757  << PrevDecl;
6758  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6759  diag::note_previous_explicit_instantiation);
6760  HasNoEffect = true;
6761  return false;
6762  }
6763  }
6764 
6765  llvm_unreachable("Missing specialization/instantiation case?");
6766 }
6767 
6768 /// \brief Perform semantic analysis for the given dependent function
6769 /// template specialization.
6770 ///
6771 /// The only possible way to get a dependent function template specialization
6772 /// is with a friend declaration, like so:
6773 ///
6774 /// \code
6775 /// template <class T> void foo(T);
6776 /// template <class T> class A {
6777 /// friend void foo<>(T);
6778 /// };
6779 /// \endcode
6780 ///
6781 /// There really isn't any useful analysis we can do here, so we
6782 /// just store the information.
6783 bool
6785  const TemplateArgumentListInfo &ExplicitTemplateArgs,
6787  // Remove anything from Previous that isn't a function template in
6788  // the correct context.
6789  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6790  LookupResult::Filter F = Previous.makeFilter();
6791  while (F.hasNext()) {
6792  NamedDecl *D = F.next()->getUnderlyingDecl();
6793  if (!isa<FunctionTemplateDecl>(D) ||
6794  !FDLookupContext->InEnclosingNamespaceSetOf(
6796  F.erase();
6797  }
6798  F.done();
6799 
6800  // Should this be diagnosed here?
6801  if (Previous.empty()) return true;
6802 
6804  ExplicitTemplateArgs);
6805  return false;
6806 }
6807 
6808 /// \brief Perform semantic analysis for the given function template
6809 /// specialization.
6810 ///
6811 /// This routine performs all of the semantic analysis required for an
6812 /// explicit function template specialization. On successful completion,
6813 /// the function declaration \p FD will become a function template
6814 /// specialization.
6815 ///
6816 /// \param FD the function declaration, which will be updated to become a
6817 /// function template specialization.
6818 ///
6819 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6820 /// if any. Note that this may be valid info even when 0 arguments are
6821 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6822 /// as it anyway contains info on the angle brackets locations.
6823 ///
6824 /// \param Previous the set of declarations that may be specialized by
6825 /// this function specialization.
6827  FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6829  // The set of function template specializations that could match this
6830  // explicit function template specialization.
6831  UnresolvedSet<8> Candidates;
6832  TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6833  /*ForTakingAddress=*/false);
6834 
6835  llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6836  ConvertedTemplateArgs;
6837 
6838  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6839  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6840  I != E; ++I) {
6841  NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6842  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6843  // Only consider templates found within the same semantic lookup scope as
6844  // FD.
6845  if (!FDLookupContext->InEnclosingNamespaceSetOf(
6846  Ovl->getDeclContext()->getRedeclContext()))
6847  continue;
6848 
6849  // When matching a constexpr member function template specialization
6850  // against the primary template, we don't yet know whether the
6851  // specialization has an implicit 'const' (because we don't know whether
6852  // it will be a static member function until we know which template it
6853  // specializes), so adjust it now assuming it specializes this template.
6854  QualType FT = FD->getType();
6855  if (FD->isConstexpr()) {
6856  CXXMethodDecl *OldMD =
6857  dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6858  if (OldMD && OldMD->isConst()) {
6859  const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6863  FPT->getParamTypes(), EPI);
6864  }
6865  }
6866 
6868  if (ExplicitTemplateArgs)
6869  Args = *ExplicitTemplateArgs;
6870 
6871  // C++ [temp.expl.spec]p11:
6872  // A trailing template-argument can be left unspecified in the
6873  // template-id naming an explicit function template specialization
6874  // provided it can be deduced from the function argument type.
6875  // Perform template argument deduction to determine whether we may be
6876  // specializing this template.
6877  // FIXME: It is somewhat wasteful to build
6878  TemplateDeductionInfo Info(FailedCandidates.getLocation());
6879  FunctionDecl *Specialization = nullptr;
6881  cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6882  ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info)) {
6883  // Template argument deduction failed; record why it failed, so
6884  // that we can provide nifty diagnostics.
6885  FailedCandidates.addCandidate()
6886  .set(FunTmpl->getTemplatedDecl(),
6887  MakeDeductionFailureInfo(Context, TDK, Info));
6888  (void)TDK;
6889  continue;
6890  }
6891 
6892  // Record this candidate.
6893  if (ExplicitTemplateArgs)
6894  ConvertedTemplateArgs[Specialization] = std::move(Args);
6895  Candidates.addDecl(Specialization, I.getAccess());
6896  }
6897  }
6898 
6899  // Find the most specialized function template.
6900  UnresolvedSetIterator Result = getMostSpecialized(
6901  Candidates.begin(), Candidates.end(), FailedCandidates,
6902  FD->getLocation(),
6903  PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6904  PDiag(diag::err_function_template_spec_ambiguous)
6905  << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6906  PDiag(diag::note_function_template_spec_matched));
6907 
6908  if (Result == Candidates.end())
6909  return true;
6910 
6911  // Ignore access information; it doesn't figure into redeclaration checking.
6912  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6913 
6915  = Specialization->getTemplateSpecializationInfo();
6916  assert(SpecInfo && "Function template specialization info missing?");
6917 
6918  // Note: do not overwrite location info if previous template
6919  // specialization kind was explicit.
6921  if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6922  Specialization->setLocation(FD->getLocation());
6923  // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6924  // function can differ from the template declaration with respect to
6925  // the constexpr specifier.
6926  Specialization->setConstexpr(FD->isConstexpr());
6927  }
6928 
6929  // FIXME: Check if the prior specialization has a point of instantiation.
6930  // If so, we have run afoul of .
6931 
6932  // If this is a friend declaration, then we're not really declaring
6933  // an explicit specialization.
6934  bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6935 
6936  // Check the scope of this explicit specialization.
6937  if (!isFriend &&
6939  Specialization->getPrimaryTemplate(),
6940  Specialization, FD->getLocation(),
6941  false))
6942  return true;
6943 
6944  // C++ [temp.expl.spec]p6:
6945  // If a template, a member template or the member of a class template is
6946  // explicitly specialized then that specialization shall be declared
6947  // before the first use of that specialization that would cause an implicit
6948  // instantiation to take place, in every translation unit in which such a
6949  // use occurs; no diagnostic is required.
6950  bool HasNoEffect = false;
6951  if (!isFriend &&
6952  CheckSpecializationInstantiationRedecl(FD->getLocation(),
6954  Specialization,
6955  SpecInfo->getTemplateSpecializationKind(),
6956  SpecInfo->getPointOfInstantiation(),
6957  HasNoEffect))
6958  return true;
6959 
6960  // Mark the prior declaration as an explicit specialization, so that later
6961  // clients know that this is an explicit specialization.
6962  if (!isFriend) {
6964  MarkUnusedFileScopedDecl(Specialization);
6965  }
6966 
6967  // Turn the given function declaration into a function template
6968  // specialization, with the template arguments from the previous
6969  // specialization.
6970  // Take copies of (semantic and syntactic) template argument lists.
6971  const TemplateArgumentList* TemplArgs = new (Context)
6972  TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6973  FD->setFunctionTemplateSpecialization(
6974  Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
6975  SpecInfo->getTemplateSpecializationKind(),
6976  ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
6977 
6978  // The "previous declaration" for this function template specialization is
6979  // the prior function template specialization.
6980  Previous.clear();
6981  Previous.addDecl(Specialization);
6982  return false;
6983 }
6984 
6985 /// \brief Perform semantic analysis for the given non-template member
6986 /// specialization.
6987 ///
6988 /// This routine performs all of the semantic analysis required for an
6989 /// explicit member function specialization. On successful completion,
6990 /// the function declaration \p FD will become a member function
6991 /// specialization.
6992 ///
6993 /// \param Member the member declaration, which will be updated to become a
6994 /// specialization.
6995 ///
6996 /// \param Previous the set of declarations, one of which may be specialized
6997 /// by this function specialization; the set will be modified to contain the
6998 /// redeclared member.
6999 bool
7001  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
7002 
7003  // Try to find the member we are instantiating.
7004  NamedDecl *Instantiation = nullptr;
7005  NamedDecl *InstantiatedFrom = nullptr;
7006  MemberSpecializationInfo *MSInfo = nullptr;
7007 
7008  if (Previous.empty()) {
7009  // Nowhere to look anyway.
7010  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
7011  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7012  I != E; ++I) {
7013  NamedDecl *D = (*I)->getUnderlyingDecl();
7014  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
7015  QualType Adjusted = Function->getType();
7016  if (!hasExplicitCallingConv(Adjusted))
7017  Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7018  if (Context.hasSameType(Adjusted, Method->getType())) {
7019  Instantiation = Method;
7020  InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
7021  MSInfo = Method->getMemberSpecializationInfo();
7022  break;
7023  }
7024  }
7025  }
7026  } else if (isa<VarDecl>(Member)) {
7027  VarDecl *PrevVar;
7028  if (Previous.isSingleResult() &&
7029  (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
7030  if (PrevVar->isStaticDataMember()) {
7031  Instantiation = PrevVar;
7032  InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
7033  MSInfo = PrevVar->getMemberSpecializationInfo();
7034  }
7035  } else if (isa<RecordDecl>(Member)) {
7036  CXXRecordDecl *PrevRecord;
7037  if (Previous.isSingleResult() &&
7038  (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7039  Instantiation = PrevRecord;
7040  InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
7041  MSInfo = PrevRecord->getMemberSpecializationInfo();
7042  }
7043  } else if (isa<EnumDecl>(Member)) {
7044  EnumDecl *PrevEnum;
7045  if (Previous.isSingleResult() &&
7046  (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7047  Instantiation = PrevEnum;
7048  InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7049  MSInfo = PrevEnum->getMemberSpecializationInfo();
7050  }
7051  }
7052 
7053  if (!Instantiation) {
7054  // There is no previous declaration that matches. Since member
7055  // specializations are always out-of-line, the caller will complain about
7056  // this mismatch later.
7057  return false;
7058  }
7059 
7060  // If this is a friend, just bail out here before we start turning
7061  // things into explicit specializations.
7062  if (Member->getFriendObjectKind() != Decl::FOK_None) {
7063  // Preserve instantiation information.
7064  if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7065  cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7066  cast<CXXMethodDecl>(InstantiatedFrom),
7067  cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7068  } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7069  cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7070  cast<CXXRecordDecl>(InstantiatedFrom),
7071  cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7072  }
7073 
7074  Previous.clear();
7075  Previous.addDecl(Instantiation);
7076  return false;
7077  }
7078 
7079  // Make sure that this is a specialization of a member.
7080  if (!InstantiatedFrom) {
7081  Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7082  << Member;
7083  Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7084  return true;
7085  }
7086 
7087  // C++ [temp.expl.spec]p6:
7088  // If a template, a member template or the member of a class template is
7089  // explicitly specialized then that specialization shall be declared
7090  // before the first use of that specialization that would cause an implicit
7091  // instantiation to take place, in every translation unit in which such a
7092  // use occurs; no diagnostic is required.
7093  assert(MSInfo && "Member specialization info missing?");
7094 
7095  bool HasNoEffect = false;
7096  if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7098  Instantiation,
7100  MSInfo->getPointOfInstantiation(),
7101  HasNoEffect))
7102  return true;
7103 
7104  // Check the scope of this explicit specialization.
7106  InstantiatedFrom,
7107  Instantiation, Member->getLocation(),
7108  false))
7109  return true;
7110 
7111  // Note that this is an explicit instantiation of a member.
7112  // the original declaration to note that it is an explicit specialization
7113  // (if it was previously an implicit instantiation). This latter step
7114  // makes bookkeeping easier.
7115  if (isa<FunctionDecl>(Member)) {
7116  FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7117  if (InstantiationFunction->getTemplateSpecializationKind() ==
7119  InstantiationFunction->setTemplateSpecializationKind(
7121  InstantiationFunction->setLocation(Member->getLocation());
7122  }
7123 
7124  cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7125  cast<CXXMethodDecl>(InstantiatedFrom),
7127  MarkUnusedFileScopedDecl(InstantiationFunction);
7128  } else if (isa<VarDecl>(Member)) {
7129  VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7130  if (InstantiationVar->getTemplateSpecializationKind() ==
7132  InstantiationVar->setTemplateSpecializationKind(
7134  InstantiationVar->setLocation(Member->getLocation());
7135  }
7136 
7137  cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7138  cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7139  MarkUnusedFileScopedDecl(InstantiationVar);
7140  } else if (isa<CXXRecordDecl>(Member)) {
7141  CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7142  if (InstantiationClass->getTemplateSpecializationKind() ==
7144  InstantiationClass->setTemplateSpecializationKind(
7146  InstantiationClass->setLocation(Member->getLocation());
7147  }
7148 
7149  cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7150  cast<CXXRecordDecl>(InstantiatedFrom),
7152  } else {
7153  assert(isa<EnumDecl>(Member) && "Only member enums remain");
7154  EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7155  if (InstantiationEnum->getTemplateSpecializationKind() ==
7157  InstantiationEnum->setTemplateSpecializationKind(
7159  InstantiationEnum->setLocation(Member->getLocation());
7160  }
7161 
7162  cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7163  cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7164  }
7165 
7166  // Save the caller the trouble of having to figure out which declaration
7167  // this specialization matches.
7168  Previous.clear();
7169  Previous.addDecl(Instantiation);
7170  return false;
7171 }
7172 
7173 /// \brief Check the scope of an explicit instantiation.
7174 ///
7175 /// \returns true if a serious error occurs, false otherwise.
7177  SourceLocation InstLoc,
7178  bool WasQualifiedName) {
7180  DeclContext *CurContext = S.CurContext->getRedeclContext();
7181 
7182  if (CurContext->isRecord()) {
7183  S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7184  << D;
7185  return true;
7186  }
7187 
7188  // C++11 [temp.explicit]p3:
7189  // An explicit instantiation shall appear in an enclosing namespace of its
7190  // template. If the name declared in the explicit instantiation is an
7191  // unqualified name, the explicit instantiation shall appear in the
7192  // namespace where its template is declared or, if that namespace is inline
7193  // (7.3.1), any namespace from its enclosing namespace set.
7194  //
7195  // This is DR275, which we do not retroactively apply to C++98/03.
7196  if (WasQualifiedName) {
7197  if (CurContext->Encloses(OrigContext))
7198  return false;
7199  } else {
7200  if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7201  return false;
7202  }
7203 
7204  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7205  if (WasQualifiedName)
7206  S.Diag(InstLoc,
7207  S.getLangOpts().CPlusPlus11?
7208  diag::err_explicit_instantiation_out_of_scope :
7209  diag::warn_explicit_instantiation_out_of_scope_0x)
7210  << D << NS;
7211  else
7212  S.Diag(InstLoc,
7213  S.getLangOpts().CPlusPlus11?
7214  diag::err_explicit_instantiation_unqualified_wrong_namespace :
7215  diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7216  << D << NS;
7217  } else
7218  S.Diag(InstLoc,
7219  S.getLangOpts().CPlusPlus11?
7220  diag::err_explicit_instantiation_must_be_global :
7221  diag::warn_explicit_instantiation_must_be_global_0x)
7222  << D;
7223  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7224  return false;
7225 }
7226 
7227 /// \brief Determine whether the given scope specifier has a template-id in it.
7229  if (!SS.isSet())
7230  return false;
7231 
7232  // C++11 [temp.explicit]p3:
7233  // If the explicit instantiation is for a member function, a member class
7234  // or a static data member of a class template specialization, the name of
7235  // the class template specialization in the qualified-id for the member
7236  // name shall be a simple-template-id.
7237  //
7238  // C++98 has the same restriction, just worded differently.
7239  for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7240  NNS = NNS->getPrefix())
7241  if (const Type *T = NNS->getAsType())
7242  if (isa<TemplateSpecializationType>(T))
7243  return true;
7244 
7245  return false;
7246 }
7247 
7248 // Explicit instantiation of a class template specialization
7249 DeclResult
7251  SourceLocation ExternLoc,
7252  SourceLocation TemplateLoc,
7253  unsigned TagSpec,
7254  SourceLocation KWLoc,
7255  const CXXScopeSpec &SS,
7256  TemplateTy TemplateD,
7257  SourceLocation TemplateNameLoc,
7258  SourceLocation LAngleLoc,
7259  ASTTemplateArgsPtr TemplateArgsIn,
7260  SourceLocation RAngleLoc,
7261  AttributeList *Attr) {
7262  // Find the class template we're specializing
7263  TemplateName Name = TemplateD.get();
7264  TemplateDecl *TD = Name.getAsTemplateDecl();
7265  // Check that the specialization uses the same tag kind as the
7266  // original template.
7268  assert(Kind != TTK_Enum &&
7269  "Invalid enum tag in class template explicit instantiation!");
7270 
7271  if (isa<TypeAliasTemplateDecl>(TD)) {
7272  Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7274  diag::note_previous_use);
7275  return true;
7276  }
7277 
7278  ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7279 
7280  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7281  Kind, /*isDefinition*/false, KWLoc,
7282  ClassTemplate->getIdentifier())) {
7283  Diag(KWLoc, diag::err_use_with_wrong_tag)
7284  << ClassTemplate
7286  ClassTemplate->getTemplatedDecl()->getKindName());
7287  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7288  diag::note_previous_use);
7289  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7290  }
7291 
7292  // C++0x [temp.explicit]p2:
7293  // There are two forms of explicit instantiation: an explicit instantiation
7294  // definition and an explicit instantiation declaration. An explicit
7295  // instantiation declaration begins with the extern keyword. [...]
7296  TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7299 
7301  // Check for dllexport class template instantiation declarations.
7302  for (AttributeList *A = Attr; A; A = A->getNext()) {
7303  if (A->getKind() == AttributeList::AT_DLLExport) {
7304  Diag(ExternLoc,
7305  diag::warn_attribute_dllexport_explicit_instantiation_decl);
7306  Diag(A->getLoc(), diag::note_attribute);
7307  break;
7308  }
7309  }
7310 
7311  if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7312  Diag(ExternLoc,
7313  diag::warn_attribute_dllexport_explicit_instantiation_decl);
7314  Diag(A->getLocation(), diag::note_attribute);
7315  }
7316  }
7317 
7318  // Translate the parser's template argument list in our AST format.
7319  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7320  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7321 
7322  // Check that the template argument list is well-formed for this
7323  // template.
7325  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7326  TemplateArgs, false, Converted))
7327  return true;
7328 
7329  // Find the class template specialization declaration that
7330  // corresponds to these arguments.
7331  void *InsertPos = nullptr;
7333  = ClassTemplate->findSpecialization(Converted, InsertPos);
7334 
7335  TemplateSpecializationKind PrevDecl_TSK
7336  = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7337 
7338  // C++0x [temp.explicit]p2:
7339  // [...] An explicit instantiation shall appear in an enclosing
7340  // namespace of its template. [...]
7341  //
7342  // This is C++ DR 275.
7343  if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7344  SS.isSet()))
7345  return true;
7346 
7347  ClassTemplateSpecializationDecl *Specialization = nullptr;
7348 
7349  bool HasNoEffect = false;
7350  if (PrevDecl) {
7351  if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7352  PrevDecl, PrevDecl_TSK,
7353  PrevDecl->getPointOfInstantiation(),
7354  HasNoEffect))
7355  return PrevDecl;
7356 
7357  // Even though HasNoEffect == true means that this explicit instantiation
7358  // has no effect on semantics, we go on to put its syntax in the AST.
7359 
7360  if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7361  PrevDecl_TSK == TSK_Undeclared) {
7362  // Since the only prior class template specialization with these
7363  // arguments was referenced but not declared, reuse that
7364  // declaration node as our own, updating the source location
7365  // for the template name to reflect our new declaration.
7366  // (Other source locations will be updated later.)
7367  Specialization = PrevDecl;
7368  Specialization->setLocation(TemplateNameLoc);
7369  PrevDecl = nullptr;
7370  }
7371  }
7372 
7373  if (!Specialization) {
7374  // Create a new class template specialization declaration node for
7375  // this explicit specialization.
7376  Specialization
7378  ClassTemplate->getDeclContext(),
7379  KWLoc, TemplateNameLoc,
7380  ClassTemplate,
7381  Converted.data(),
7382  Converted.size(),
7383  PrevDecl);
7384  SetNestedNameSpecifier(Specialization, SS);
7385 
7386  if (!HasNoEffect && !PrevDecl) {
7387  // Insert the new specialization.
7388  ClassTemplate->AddSpecialization(Specialization, InsertPos);
7389  }
7390  }
7391 
7392  // Build the fully-sugared type for this explicit instantiation as
7393  // the user wrote in the explicit instantiation itself. This means
7394  // that we'll pretty-print the type retrieved from the
7395  // specialization's declaration the way that the user actually wrote
7396  // the explicit instantiation, rather than formatting the name based
7397  // on the "canonical" representation used to store the template
7398  // arguments in the specialization.
7399  TypeSourceInfo *WrittenTy
7400  = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7401  TemplateArgs,
7402  Context.getTypeDeclType(Specialization));
7403  Specialization->setTypeAsWritten(WrittenTy);
7404 
7405  // Set source locations for keywords.
7406  Specialization->setExternLoc(ExternLoc);
7407  Specialization->setTemplateKeywordLoc(TemplateLoc);
7408  Specialization->setRBraceLoc(SourceLocation());
7409 
7410  if (Attr)
7411  ProcessDeclAttributeList(S, Specialization, Attr);
7412 
7413  // Add the explicit instantiation into its lexical context. However,
7414  // since explicit instantiations are never found by name lookup, we
7415  // just put it into the declaration context directly.
7416  Specialization->setLexicalDeclContext(CurContext);
7417  CurContext->addDecl(Specialization);
7418 
7419  // Syntax is now OK, so return if it has no other effect on semantics.
7420  if (HasNoEffect) {
7421  // Set the template specialization kind.
7422  Specialization->setTemplateSpecializationKind(TSK);
7423  return Specialization;
7424  }
7425 
7426  // C++ [temp.explicit]p3:
7427  // A definition of a class template or class member template
7428  // shall be in scope at the point of the explicit instantiation of
7429  // the class template or class member template.
7430  //
7431  // This check comes when we actually try to perform the
7432  // instantiation.
7434  = cast_or_null<ClassTemplateSpecializationDecl>(
7435  Specialization->getDefinition());
7436  if (!Def)
7437  InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7438  else if (TSK == TSK_ExplicitInstantiationDefinition) {
7439  MarkVTableUsed(TemplateNameLoc, Specialization, true);
7440  Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7441  }
7442 
7443  // Instantiate the members of this class template specialization.
7444  Def = cast_or_null<ClassTemplateSpecializationDecl>(
7445  Specialization->getDefinition());
7446  if (Def) {
7448 
7449  // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7450  // TSK_ExplicitInstantiationDefinition
7451  if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7453  // FIXME: Need to notify the ASTMutationListener that we did this.
7455 
7456  if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7458  // In the MS ABI, an explicit instantiation definition can add a dll
7459  // attribute to a template with a previous instantiation declaration.
7460  // MinGW doesn't allow this.
7461  auto *A = cast<InheritableAttr>(
7462  getDLLAttr(Specialization)->clone(getASTContext()));
7463  A->setInherited(true);
7464  Def->addAttr(A);
7465  checkClassLevelDLLAttribute(Def);
7466 
7467  // Propagate attribute to base class templates.
7468  for (auto &B : Def->bases()) {
7469  if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7470  B.getType()->getAsCXXRecordDecl()))
7471  propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7472  }
7473  }
7474  }
7475 
7476  // Set the template specialization kind. Make sure it is set before
7477  // instantiating the members which will trigger ASTConsumer callbacks.
7478  Specialization->setTemplateSpecializationKind(TSK);
7479  InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7480  } else {
7481 
7482  // Set the template specialization kind.
7483  Specialization->setTemplateSpecializationKind(TSK);
7484  }
7485 
7486  return Specialization;
7487 }
7488 
7489 // Explicit instantiation of a member class of a class template.
7490 DeclResult
7492  SourceLocation ExternLoc,
7493  SourceLocation TemplateLoc,
7494  unsigned TagSpec,
7495  SourceLocation KWLoc,
7496  CXXScopeSpec &SS,
7498  SourceLocation NameLoc,
7499  AttributeList *Attr) {
7500 
7501  bool Owned = false;
7502  bool IsDependent = false;
7503  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7504  KWLoc, SS, Name, NameLoc, Attr, AS_none,
7505  /*ModulePrivateLoc=*/SourceLocation(),
7506  MultiTemplateParamsArg(), Owned, IsDependent,
7507  SourceLocation(), false, TypeResult(),
7508  /*IsTypeSpecifier*/false);
7509  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7510 
7511  if (!TagD)
7512  return true;
7513 
7514  TagDecl *Tag = cast<TagDecl>(TagD);
7515  assert(!Tag->isEnum() && "shouldn't see enumerations here");
7516 
7517  if (Tag->isInvalidDecl())
7518  return true;
7519 
7520  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7521  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7522  if (!Pattern) {
7523  Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7524  << Context.getTypeDeclType(Record);
7525  Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7526  return true;
7527  }
7528 
7529  // C++0x [temp.explicit]p2:
7530  // If the explicit instantiation is for a class or member class, the
7531  // elaborated-type-specifier in the declaration shall include a
7532  // simple-template-id.
7533  //
7534  // C++98 has the same restriction, just worded differently.
7535  if (!ScopeSpecifierHasTemplateId(SS))
7536  Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7537  << Record << SS.getRange();
7538 
7539  // C++0x [temp.explicit]p2:
7540  // There are two forms of explicit instantiation: an explicit instantiation
7541  // definition and an explicit instantiation declaration. An explicit
7542  // instantiation declaration begins with the extern keyword. [...]
7546 
7547  // C++0x [temp.explicit]p2:
7548  // [...] An explicit instantiation shall appear in an enclosing
7549  // namespace of its template. [...]
7550  //
7551  // This is C++ DR 275.
7552  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7553 
7554  // Verify that it is okay to explicitly instantiate here.
7555  CXXRecordDecl *PrevDecl
7556  = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7557  if (!PrevDecl && Record->getDefinition())
7558  PrevDecl = Record;
7559  if (PrevDecl) {
7561  bool HasNoEffect = false;
7562  assert(MSInfo && "No member specialization information?");
7563  if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7564  PrevDecl,
7566  MSInfo->getPointOfInstantiation(),
7567  HasNoEffect))
7568  return true;
7569  if (HasNoEffect)
7570  return TagD;
7571  }
7572 
7573  CXXRecordDecl *RecordDef
7574  = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7575  if (!RecordDef) {
7576  // C++ [temp.explicit]p3:
7577  // A definition of a member class of a class template shall be in scope
7578  // at the point of an explicit instantiation of the member class.
7579  CXXRecordDecl *Def
7580  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7581  if (!Def) {
7582  Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7583  << 0 << Record->getDeclName() << Record->getDeclContext();
7584  Diag(Pattern->getLocation(), diag::note_forward_declaration)
7585  << Pattern;
7586  return true;
7587  } else {
7588  if (InstantiateClass(NameLoc, Record, Def,
7589  getTemplateInstantiationArgs(Record),
7590  TSK))
7591  return true;
7592 
7593  RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7594  if (!RecordDef)
7595  return true;
7596  }
7597  }
7598 
7599  // Instantiate all of the members of the class.
7600  InstantiateClassMembers(NameLoc, RecordDef,
7601  getTemplateInstantiationArgs(Record), TSK);
7602 
7604  MarkVTableUsed(NameLoc, RecordDef, true);
7605 
7606  // FIXME: We don't have any representation for explicit instantiations of
7607  // member classes. Such a representation is not needed for compilation, but it
7608  // should be available for clients that want to see all of the declarations in
7609  // the source code.
7610  return TagD;
7611 }
7612 
7614  SourceLocation ExternLoc,
7615  SourceLocation TemplateLoc,
7616  Declarator &D) {
7617  // Explicit instantiations always require a name.
7618  // TODO: check if/when DNInfo should replace Name.
7619  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7620  DeclarationName Name = NameInfo.getName();
7621  if (!Name) {
7622  if (!D.isInvalidType())
7624  diag::err_explicit_instantiation_requires_name)
7625  << D.getDeclSpec().getSourceRange()
7626  << D.getSourceRange();
7627 
7628  return true;
7629  }
7630 
7631  // The scope passed in may not be a decl scope. Zip up the scope tree until
7632  // we find one that is.
7633  while ((S->getFlags() & Scope::DeclScope) == 0 ||
7634  (S->getFlags() & Scope::TemplateParamScope) != 0)
7635  S = S->getParent();
7636 
7637  // Determine the type of the declaration.
7638  TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7639  QualType R = T->getType();
7640  if (R.isNull())
7641  return true;
7642 
7643  // C++ [dcl.stc]p1:
7644  // A storage-class-specifier shall not be specified in [...] an explicit
7645  // instantiation (14.7.2) directive.
7647  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7648  << Name;
7649  return true;
7650  } else if (D.getDeclSpec().getStorageClassSpec()
7652  // Complain about then remove the storage class specifier.
7653  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7655 
7657  }
7658 
7659  // C++0x [temp.explicit]p1:
7660  // [...] An explicit instantiation of a function template shall not use the
7661  // inline or constexpr specifiers.
7662  // Presumably, this also applies to member functions of class templates as
7663  // well.
7664  if (D.getDeclSpec().isInlineSpecified())
7666  getLangOpts().CPlusPlus11 ?
7667  diag::err_explicit_instantiation_inline :
7668  diag::warn_explicit_instantiation_inline_0x)
7671  // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7672  // not already specified.
7674  diag::err_explicit_instantiation_constexpr);
7675 
7676  // C++0x [temp.explicit]p2:
7677  // There are two forms of explicit instantiation: an explicit instantiation
7678  // definition and an explicit instantiation declaration. An explicit
7679  // instantiation declaration begins with the extern keyword. [...]
7683 
7684  LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7685  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7686 
7687  if (!R->isFunctionType()) {
7688  // C++ [temp.explicit]p1:
7689  // A [...] static data member of a class template can be explicitly
7690  // instantiated from the member definition associated with its class
7691  // template.
7692  // C++1y [temp.explicit]p1:
7693  // A [...] variable [...] template specialization can be explicitly
7694  // instantiated from its template.
7695  if (Previous.isAmbiguous())
7696  return true;
7697 
7698  VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7699  VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7700 
7701  if (!PrevTemplate) {
7702  if (!Prev || !Prev->isStaticDataMember()) {
7703  // We expect to see a data data member here.
7704  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7705  << Name;
7706  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7707  P != PEnd; ++P)
7708  Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7709  return true;
7710  }
7711 
7712  if (!Prev->getInstantiatedFromStaticDataMember()) {
7713  // FIXME: Check for explicit specialization?
7714  Diag(D.getIdentifierLoc(),
7715  diag::err_explicit_instantiation_data_member_not_instantiated)
7716  << Prev;
7717  Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7718  // FIXME: Can we provide a note showing where this was declared?
7719  return true;
7720  }
7721  } else {
7722  // Explicitly instantiate a variable template.
7723 
7724  // C++1y [dcl.spec.auto]p6:
7725  // ... A program that uses auto or decltype(auto) in a context not
7726  // explicitly allowed in this section is ill-formed.
7727  //
7728  // This includes auto-typed variable template instantiations.
7729  if (R->isUndeducedType()) {
7730  Diag(T->getTypeLoc().getLocStart(),
7731  diag::err_auto_not_allowed_var_inst);
7732  return true;
7733  }
7734 
7736  // C++1y [temp.explicit]p3:
7737  // If the explicit instantiation is for a variable, the unqualified-id
7738  // in the declaration shall be a template-id.
7739  Diag(D.getIdentifierLoc(),
7740  diag::err_explicit_instantiation_without_template_id)
7741  << PrevTemplate;
7742  Diag(PrevTemplate->getLocation(),
7743  diag::note_explicit_instantiation_here);
7744  return true;
7745  }
7746 
7747  // Translate the parser's template argument list into our AST format.
7748  TemplateArgumentListInfo TemplateArgs =
7750 
7751  DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7752  D.getIdentifierLoc(), TemplateArgs);
7753  if (Res.isInvalid())
7754  return true;
7755 
7756  // Ignore access control bits, we don't need them for redeclaration
7757  // checking.
7758  Prev = cast<VarDecl>(Res.get());
7759  }
7760 
7761  // C++0x [temp.explicit]p2:
7762  // If the explicit instantiation is for a member function, a member class
7763  // or a static data member of a class template specialization, the name of
7764  // the class template specialization in the qualified-id for the member
7765  // name shall be a simple-template-id.
7766  //
7767  // C++98 has the same restriction, just worded differently.
7768  //
7769  // This does not apply to variable template specializations, where the
7770  // template-id is in the unqualified-id instead.
7771  if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7772  Diag(D.getIdentifierLoc(),
7773  diag::ext_explicit_instantiation_without_qualified_id)
7774  << Prev << D.getCXXScopeSpec().getRange();
7775 
7776  // Check the scope of this explicit instantiation.
7777  CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7778 
7779  // Verify that it is okay to explicitly instantiate here.
7782  bool HasNoEffect = false;
7783  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7784  PrevTSK, POI, HasNoEffect))
7785  return true;
7786 
7787  if (!HasNoEffect) {
7788  // Instantiate static data member or variable template.
7789 
7790  Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7791  if (PrevTemplate) {
7792  // Merge attributes.
7794  ProcessDeclAttributeList(S, Prev, Attr);
7795  }
7797  InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7798  }
7799 
7800  // Check the new variable specialization against the parsed input.
7801  if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7802  Diag(T->getTypeLoc().getLocStart(),
7803  diag::err_invalid_var_template_spec_type)
7804  << 0 << PrevTemplate << R << Prev->getType();
7805  Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7806  << 2 << PrevTemplate->getDeclName();
7807  return true;
7808  }
7809 
7810  // FIXME: Create an ExplicitInstantiation node?
7811  return (Decl*) nullptr;
7812  }
7813 
7814  // If the declarator is a template-id, translate the parser's template
7815  // argument list into our AST format.
7816  bool HasExplicitTemplateArgs = false;
7817  TemplateArgumentListInfo TemplateArgs;
7819  TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7820  HasExplicitTemplateArgs = true;
7821  }
7822 
7823  // C++ [temp.explicit]p1:
7824  // A [...] function [...] can be explicitly instantiated from its template.
7825  // A member function [...] of a class template can be explicitly
7826  // instantiated from the member definition associated with its class
7827  // template.
7829  TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7830  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7831  P != PEnd; ++P) {
7832  NamedDecl *Prev = *P;
7833  if (!HasExplicitTemplateArgs) {
7834  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7835  QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7836  if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7837  Matches.clear();
7838 
7839  Matches.addDecl(Method, P.getAccess());
7840  if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7841  break;
7842  }
7843  }
7844  }
7845 
7846  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7847  if (!FunTmpl)
7848  continue;
7849 
7850  TemplateDeductionInfo Info(FailedCandidates.getLocation());
7851  FunctionDecl *Specialization = nullptr;
7852  if (TemplateDeductionResult TDK
7853  = DeduceTemplateArguments(FunTmpl,
7854  (HasExplicitTemplateArgs ? &TemplateArgs
7855  : nullptr),
7856  R, Specialization, Info)) {
7857  // Keep track of almost-matches.
7858  FailedCandidates.addCandidate()
7859  .set(FunTmpl->getTemplatedDecl(),
7860  MakeDeductionFailureInfo(Context, TDK, Info));
7861  (void)TDK;
7862  continue;
7863  }
7864 
7865  Matches.addDecl(Specialization, P.getAccess());
7866  }
7867 
7868  // Find the most specialized function template specialization.
7869  UnresolvedSetIterator Result = getMostSpecialized(
7870  Matches.begin(), Matches.end(), FailedCandidates,
7871  D.getIdentifierLoc(),
7872  PDiag(diag::err_explicit_instantiation_not_known) << Name,
7873  PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7874  PDiag(diag::note_explicit_instantiation_candidate));
7875 
7876  if (Result == Matches.end())
7877  return true;
7878 
7879  // Ignore access control bits, we don't need them for redeclaration checking.
7880  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7881 
7882  // C++11 [except.spec]p4
7883  // In an explicit instantiation an exception-specification may be specified,
7884  // but is not required.
7885  // If an exception-specification is specified in an explicit instantiation
7886  // directive, it shall be compatible with the exception-specifications of
7887  // other declarations of that function.
7888  if (auto *FPT = R->getAs<FunctionProtoType>())
7889  if (FPT->hasExceptionSpec()) {
7890  unsigned DiagID =
7891  diag::err_mismatched_exception_spec_explicit_instantiation;
7892  if (getLangOpts().MicrosoftExt)
7893  DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7894  bool Result = CheckEquivalentExceptionSpec(
7895  PDiag(DiagID) << Specialization->getType(),
7896  PDiag(diag::note_explicit_instantiation_here),
7897  Specialization->getType()->getAs<FunctionProtoType>(),
7898  Specialization->getLocation(), FPT, D.getLocStart());
7899  // In Microsoft mode, mismatching exception specifications just cause a
7900  // warning.
7901  if (!getLangOpts().MicrosoftExt && Result)
7902  return true;
7903  }
7904 
7905  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7906  Diag(D.getIdentifierLoc(),
7907  diag::err_explicit_instantiation_member_function_not_instantiated)
7908  << Specialization
7909  << (Specialization->getTemplateSpecializationKind() ==
7911  Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7912  return true;
7913  }
7914 
7915  FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7916  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7917  PrevDecl = Specialization;
7918 
7919  if (PrevDecl) {
7920  bool HasNoEffect = false;
7921  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7922  PrevDecl,
7923  PrevDecl->getTemplateSpecializationKind(),
7924  PrevDecl->getPointOfInstantiation(),
7925  HasNoEffect))
7926  return true;
7927 
7928  // FIXME: We may still want to build some representation of this
7929  // explicit specialization.
7930  if (HasNoEffect)
7931  return (Decl*) nullptr;
7932  }
7933 
7934  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7936  if (Attr)
7937  ProcessDeclAttributeList(S, Specialization, Attr);
7938 
7939  if (Specialization->isDefined()) {
7940  // Let the ASTConsumer know that this function has been explicitly
7941  // instantiated now, and its linkage might have changed.
7942  Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7943  } else if (TSK == TSK_ExplicitInstantiationDefinition)
7944  InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7945 
7946  // C++0x [temp.explicit]p2:
7947  // If the explicit instantiation is for a member function, a member class
7948  // or a static data member of a class template specialization, the name of
7949  // the class template specialization in the qualified-id for the member
7950  // name shall be a simple-template-id.
7951  //
7952  // C++98 has the same restriction, just worded differently.
7953  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7954  if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7955  D.getCXXScopeSpec().isSet() &&
7957  Diag(D.getIdentifierLoc(),
7958  diag::ext_explicit_instantiation_without_qualified_id)
7959  << Specialization << D.getCXXScopeSpec().getRange();
7960 
7962  FunTmpl? (NamedDecl *)FunTmpl
7963  : Specialization->getInstantiatedFromMemberFunction(),
7964  D.getIdentifierLoc(),
7965  D.getCXXScopeSpec().isSet());
7966 
7967  // FIXME: Create some kind of ExplicitInstantiationDecl here.
7968  return (Decl*) nullptr;
7969 }
7970 
7971 TypeResult
7972 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7973  const CXXScopeSpec &SS, IdentifierInfo *Name,
7974  SourceLocation TagLoc, SourceLocation NameLoc) {
7975  // This has to hold, because SS is expected to be defined.
7976  assert(Name && "Expected a name in a dependent tag");
7977 
7978  NestedNameSpecifier *NNS = SS.getScopeRep();
7979  if (!NNS)
7980  return true;
7981 
7983 
7984  if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7985  Diag(NameLoc, diag::err_dependent_tag_decl)
7986  << (TUK == TUK_Definition) << Kind << SS.getRange();
7987  return true;
7988  }
7989 
7990  // Create the resulting type.
7992  QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7993 
7994  // Create type-source location information for this type.
7995  TypeLocBuilder TLB;
7997  TL.setElaboratedKeywordLoc(TagLoc);
7999  TL.setNameLoc(NameLoc);
8000  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
8001 }
8002 
8003 TypeResult
8005  const CXXScopeSpec &SS, const IdentifierInfo &II,
8006  SourceLocation IdLoc) {
8007  if (SS.isInvalid())
8008  return true;
8009 
8010  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8011  Diag(TypenameLoc,
8012  getLangOpts().CPlusPlus11 ?
8013  diag::warn_cxx98_compat_typename_outside_of_template :
8014  diag::ext_typename_outside_of_template)
8015  << FixItHint::CreateRemoval(TypenameLoc);
8016 
8018  QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8019  TypenameLoc, QualifierLoc, II, IdLoc);
8020  if (T.isNull())
8021  return true;
8022 
8024  if (isa<DependentNameType>(T)) {
8026  TL.setElaboratedKeywordLoc(TypenameLoc);
8027  TL.setQualifierLoc(QualifierLoc);
8028  TL.setNameLoc(IdLoc);
8029  } else {
8031  TL.setElaboratedKeywordLoc(TypenameLoc);
8032  TL.setQualifierLoc(QualifierLoc);
8033  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
8034  }
8035 
8036  return CreateParsedType(T, TSI);
8037 }
8038 
8039 TypeResult
8041  SourceLocation TypenameLoc,
8042  const CXXScopeSpec &SS,
8043  SourceLocation TemplateKWLoc,
8044  TemplateTy TemplateIn,
8045  SourceLocation TemplateNameLoc,
8046  SourceLocation LAngleLoc,
8047  ASTTemplateArgsPtr TemplateArgsIn,
8048  SourceLocation RAngleLoc) {
8049  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8050  Diag(TypenameLoc,
8051  getLangOpts().CPlusPlus11 ?
8052  diag::warn_cxx98_compat_typename_outside_of_template :
8053  diag::ext_typename_outside_of_template)
8054  << FixItHint::CreateRemoval(TypenameLoc);
8055 
8056  // Translate the parser's template argument list in our AST format.
8057  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8058  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8059 
8060  TemplateName Template = TemplateIn.get();
8061  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8062  // Construct a dependent template specialization type.
8063  assert(DTN && "dependent template has non-dependent name?");
8064  assert(DTN->getQualifier() == SS.getScopeRep());
8066  DTN->getQualifier(),
8067  DTN->getIdentifier(),
8068  TemplateArgs);
8069 
8070  // Create source-location information for this type.
8074  SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8076  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8077  SpecTL.setTemplateNameLoc(TemplateNameLoc);
8078  SpecTL.setLAngleLoc(LAngleLoc);
8079  SpecTL.setRAngleLoc(RAngleLoc);
8080  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8081  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8082  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
8083  }
8084 
8085  QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8086  if (T.isNull())
8087  return true;
8088 
8089  // Provide source-location information for the template specialization type.
8092  = Builder.push<TemplateSpecializationTypeLoc>(T);
8093  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8094  SpecTL.setTemplateNameLoc(TemplateNameLoc);
8095  SpecTL.setLAngleLoc(LAngleLoc);
8096  SpecTL.setRAngleLoc(RAngleLoc);
8097  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8098  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8099 
8101  ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
8102  TL.setElaboratedKeywordLoc(TypenameLoc);
8104 
8105  TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8106  return CreateParsedType(T, TSI);
8107 }
8108 
8109 
8110 /// Determine whether this failed name lookup should be treated as being
8111 /// disabled by a usage of std::enable_if.
8113  SourceRange &CondRange) {
8114  // We must be looking for a ::type...
8115  if (!II.isStr("type"))
8116  return false;
8117 
8118  // ... within an explicitly-written template specialization...
8119  if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8120  return false;
8121  TypeLoc EnableIfTy = NNS.getTypeLoc();
8122  TemplateSpecializationTypeLoc EnableIfTSTLoc =
8123  EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8124  if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8125  return false;
8126  const TemplateSpecializationType *EnableIfTST =
8127  cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8128 
8129  // ... which names a complete class template declaration...
8130  const TemplateDecl *EnableIfDecl =
8131  EnableIfTST->getTemplateName().getAsTemplateDecl();
8132  if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8133  return false;
8134 
8135  // ... called "enable_if".
8136  const IdentifierInfo *EnableIfII =
8137  EnableIfDecl->getDeclName().getAsIdentifierInfo();
8138  if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8139  return false;
8140 
8141  // Assume the first template argument is the condition.
8142  CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8143  return true;
8144 }
8145 
8146 /// \brief Build the type that describes a C++ typename specifier,
8147 /// e.g., "typename T::type".
8148 QualType
8150  SourceLocation KeywordLoc,
8151  NestedNameSpecifierLoc QualifierLoc,
8152  const IdentifierInfo &II,
8153  SourceLocation IILoc) {
8154  CXXScopeSpec SS;
8155  SS.Adopt(QualifierLoc);
8156 
8157  DeclContext *Ctx = computeDeclContext(SS);
8158  if (!Ctx) {
8159  // If the nested-name-specifier is dependent and couldn't be
8160  // resolved to a type, build a typename type.
8161  assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8162  return Context.getDependentNameType(Keyword,
8163  QualifierLoc.getNestedNameSpecifier(),
8164  &II);
8165  }
8166 
8167  // If the nested-name-specifier refers to the current instantiation,
8168  // the "typename" keyword itself is superfluous. In C++03, the
8169  // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8170  // allows such extraneous "typename" keywords, and we retroactively
8171  // apply this DR to C++03 code with only a warning. In any case we continue.
8172 
8173  if (RequireCompleteDeclContext(SS, Ctx))
8174  return QualType();
8175 
8176  DeclarationName Name(&II);
8177  LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8178  LookupQualifiedName(Result, Ctx, SS);
8179  unsigned DiagID = 0;
8180  Decl *Referenced = nullptr;
8181  switch (Result.getResultKind()) {
8182  case LookupResult::NotFound: {
8183  // If we're looking up 'type' within a template named 'enable_if', produce
8184  // a more specific diagnostic.
8185  SourceRange CondRange;
8186  if (isEnableIf(QualifierLoc, II, CondRange)) {
8187  Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8188  << Ctx << CondRange;
8189  return QualType();
8190  }
8191 
8192  DiagID = diag::err_typename_nested_not_found;
8193  break;
8194  }
8195 
8197  // We found a using declaration that is a value. Most likely, the using
8198  // declaration itself is meant to have the 'typename' keyword.
8199  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8200  IILoc);
8201  Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8202  << Name << Ctx << FullRange;
8203  if (UnresolvedUsingValueDecl *Using
8204  = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8205  SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8206  Diag(Loc, diag::note_using_value_decl_missing_typename)
8207  << FixItHint::CreateInsertion(Loc, "typename ");
8208  }
8209  }
8210  // Fall through to create a dependent typename type, from which we can recover
8211  // better.
8212 
8214  // Okay, it's a member of an unknown instantiation.
8215  return Context.getDependentNameType(Keyword,
8216  QualifierLoc.getNestedNameSpecifier(),
8217  &II);
8218 
8219  case LookupResult::Found:
8220  if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8221  // We found a type. Build an ElaboratedType, since the
8222  // typename-specifier was just sugar.
8223  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8225  QualifierLoc.getNestedNameSpecifier(),
8227  }
8228 
8229  DiagID = diag::err_typename_nested_not_type;
8230  Referenced = Result.getFoundDecl();
8231  break;
8232 
8234  DiagID = diag::err_typename_nested_not_type;
8235  Referenced = *Result.begin();
8236  break;
8237 
8239  return QualType();
8240  }
8241 
8242  // If we get here, it's because name lookup did not find a
8243  // type. Emit an appropriate diagnostic and return an error.
8244  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8245  IILoc);
8246  Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8247  if (Referenced)
8248  Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8249  << Name;
8250  return QualType();
8251 }
8252 
8253 namespace {
8254  // See Sema::RebuildTypeInCurrentInstantiation
8255  class CurrentInstantiationRebuilder
8256  : public TreeTransform<CurrentInstantiationRebuilder> {
8257  SourceLocation Loc;
8258  DeclarationName Entity;
8259 
8260  public:
8262 
8263  CurrentInstantiationRebuilder(Sema &SemaRef,
8264  SourceLocation Loc,
8265  DeclarationName Entity)
8266  : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8267  Loc(Loc), Entity(Entity) { }
8268 
8269  /// \brief Determine whether the given type \p T has already been
8270  /// transformed.
8271  ///
8272  /// For the purposes of type reconstruction, a type has already been
8273  /// transformed if it is NULL or if it is not dependent.
8274  bool AlreadyTransformed(QualType T) {
8275  return T.isNull() || !T->isDependentType();
8276  }
8277 
8278  /// \brief Returns the location of the entity whose type is being
8279  /// rebuilt.
8280  SourceLocation getBaseLocation() { return Loc; }
8281 
8282  /// \brief Returns the name of the entity whose type is being rebuilt.
8283  DeclarationName getBaseEntity() { return Entity; }
8284 
8285  /// \brief Sets the "base" location and entity when that
8286  /// information is known based on another transformation.
8287  void setBase(SourceLocation Loc, DeclarationName Entity) {
8288  this->Loc = Loc;
8289  this->Entity = Entity;
8290  }
8291 
8292  ExprResult TransformLambdaExpr(LambdaExpr *E) {
8293  // Lambdas never need to be transformed.
8294  return E;
8295  }
8296  };
8297 }
8298 
8299 /// \brief Rebuilds a type within the context of the current instantiation.
8300 ///
8301 /// The type \p T is part of the type of an out-of-line member definition of
8302 /// a class template (or class template partial specialization) that was parsed
8303 /// and constructed before we entered the scope of the class template (or
8304 /// partial specialization thereof). This routine will rebuild that type now
8305 /// that we have entered the declarator's scope, which may produce different
8306 /// canonical types, e.g.,
8307 ///
8308 /// \code
8309 /// template<typename T>
8310 /// struct X {
8311 /// typedef T* pointer;
8312 /// pointer data();
8313 /// };
8314 ///
8315 /// template<typename T>
8316 /// typename X<T>::pointer X<T>::data() { ... }
8317 /// \endcode
8318 ///
8319 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8320 /// since we do not know that we can look into X<T> when we parsed the type.
8321 /// This function will rebuild the type, performing the lookup of "pointer"
8322 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8323 /// as the canonical type of T*, allowing the return types of the out-of-line
8324 /// definition and the declaration to match.
8326  SourceLocation Loc,
8328  if (!T || !T->getType()->isDependentType())
8329  return T;
8330 
8331  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8332  return Rebuilder.TransformType(T);
8333 }
8334 
8336  CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8337  DeclarationName());
8338  return Rebuilder.TransformExpr(E);
8339 }
8340 
8342  if (SS.isInvalid())
8343  return true;
8344 
8346  CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8347  DeclarationName());
8348  NestedNameSpecifierLoc Rebuilt
8349  = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8350  if (!Rebuilt)
8351  return true;
8352 
8353  SS.Adopt(Rebuilt);
8354  return false;
8355 }
8356 
8357 /// \brief Rebuild the template parameters now that we know we're in a current
8358 /// instantiation.
8360  TemplateParameterList *Params) {
8361  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8362  Decl *Param = Params->getParam(I);
8363 
8364  // There is nothing to rebuild in a type parameter.
8365  if (isa<TemplateTypeParmDecl>(Param))
8366  continue;
8367 
8368  // Rebuild the template parameter list of a template template parameter.
8369  if (TemplateTemplateParmDecl *TTP
8370  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8371  if (RebuildTemplateParamsInCurrentInstantiation(
8372  TTP->getTemplateParameters()))
8373  return true;
8374 
8375  continue;
8376  }
8377 
8378  // Rebuild the type of a non-type template parameter.
8379  NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8380  TypeSourceInfo *NewTSI
8381  = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8382  NTTP->getLocation(),
8383  NTTP->getDeclName());
8384  if (!NewTSI)
8385  return true;
8386 
8387  if (NewTSI != NTTP->getTypeSourceInfo()) {
8388  NTTP->setTypeSourceInfo(NewTSI);
8389  NTTP->setType(NewTSI->getType());
8390  }
8391  }
8392 
8393  return false;
8394 }
8395 
8396 /// \brief Produces a formatted string that describes the binding of
8397 /// template parameters to template arguments.
8398 std::string
8400  const TemplateArgumentList &Args) {
8401  return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8402 }
8403 
8404 std::string
8406  const TemplateArgument *Args,
8407  unsigned NumArgs) {
8408  SmallString<128> Str;
8409  llvm::raw_svector_ostream Out(Str);
8410 
8411  if (!Params || Params->size() == 0 || NumArgs == 0)
8412  return std::string();
8413 
8414  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8415  if (I >= NumArgs)
8416  break;
8417 
8418  if (I == 0)
8419  Out << "[with ";
8420  else
8421  Out << ", ";
8422 
8423  if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8424  Out << Id->getName();
8425  } else {
8426  Out << '$' << I;
8427  }
8428 
8429  Out << " = ";
8430  Args[I].print(getPrintingPolicy(), Out);
8431  }
8432 
8433  Out << ']';
8434  return Out.str();
8435 }
8436 
8438  CachedTokens &Toks) {
8439  if (!FD)
8440  return;
8441 
8443 
8444  // Take tokens to avoid allocations
8445  LPT->Toks.swap(Toks);
8446  LPT->D = FnD;
8447  LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8448 
8449  FD->setLateTemplateParsed(true);
8450 }
8451 
8453  if (!FD)
8454  return;
8455  FD->setLateTemplateParsed(false);
8456 }
8457 
8459  DeclContext *DC = CurContext;
8460 
8461  while (DC) {
8462  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8463  const FunctionDecl *FD = RD->isLocalClass();
8464  return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8465  } else if (DC->isTranslationUnit() || DC->isNamespace())
8466  return false;
8467 
8468  DC = DC->getParent();
8469  }
8470  return false;
8471 }
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:265
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:207
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:5383
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType) const
ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
Defines the clang::ASTContext interface.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:465
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:489
IdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:971
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:454
Name lookup found a set of overloaded functions that met the criteria.
Definition: Sema/Lookup.h:47
int Position
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
BuiltinTemplateKind getBuiltinTemplateKind() const
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:916
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:1807
bool isNullPtrType() const
Definition: Type.h:5559
unsigned getDepth() const
Definition: Type.h:3779
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2147
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:3332
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization, retrieves the member specialization information.
Definition: DeclCXX.cpp:1221
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2262
A (possibly-)qualified type.
Definition: Type.h:575
Simple class containing the result of Sema::CorrectTypo.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:6287
base_class_range bases()
Definition: DeclCXX.h:713
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< Decl * > Params, SourceLocation RAngleLoc)
ActOnTemplateParameterList - Builds a TemplateParameterList that contains the template parameters in ...
bool isInvalid() const
Definition: Ownership.h:159
void setDefaultArgument(TypeSourceInfo *DefArg)
Set the default argument for this template parameter.
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:282
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1077
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:178
bool isMemberPointerType() const
Definition: Type.h:5329
bool isSuppressingDiagnostics() const
Determines whether this lookup is suppressing diagnostics.
Definition: Sema/Lookup.h:528
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static CXXDependentScopeMemberExpr * Create(const ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1207
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2636
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:164
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:96
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1673
const LangOptions & getLangOpts() const
Definition: Sema.h:1041
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Sema/Lookup.h:209
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedType getAsType() const
Retrieve the template type argument's type.
static UnresolvedLookupExpr * Create(const ASTContext &C, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool ADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.h:2634
DeclClass * getAsSingle() const
Definition: Sema/Lookup.h:448
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Sema/Lookup.h:465
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:921
Filter makeFilter()
Create a filter for this result set.
Definition: Sema/Lookup.h:622
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:935
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1458
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1680
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:5844
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:1759
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
Provides information about an attempted template argument deduction, whose success or failure was des...
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:215
The name refers to a dependent template name.
Definition: TemplateKinds.h:38
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:4328
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:293
The template argument is an expression, and we've not resolved it to one of the other forms yet...
Definition: TemplateBase.h:69
CXXRecordDecl * getDecl() const
Definition: Type.cpp:3060
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
void erase()
Erase the last element returned from this iterator.
Definition: Sema/Lookup.h:594
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
QualType getUnderlyingType() const
Definition: Decl.h:2566
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1118
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:77
bool isChar16Type() const
Definition: Type.cpp:1666
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:2586
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Defines the C++ template declaration subclasses.
void setModulePrivate(bool MP=true)
Specify whether this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:570
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:3918
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
bool isEnumeralType() const
Definition: Type.h:5365
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
Not a friend object.
Definition: DeclBase.h:969
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1605
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:834
SCS getStorageClassSpec() const
Definition: DeclSpec.h:441
void AddDecl(Decl *D)
Definition: Scope.h:272
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization...
Definition: Decl.h:3143
std::string getAsString() const
Definition: Type.h:901
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:315
PtrTy get() const
Definition: Ownership.h:163
TemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon, QualType Aliased)
Definition: Type.cpp:3118
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:2398
QualType getPointeeType() const
Definition: Type.h:2388
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
The base class of the type hierarchy.
Definition: Type.h:1249
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, const TemplateArgument *Args, unsigned NumArgs, ClassTemplateSpecializationDecl *PrevDecl)
bool isMemberPointer() const
Definition: APValue.h:191
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:884
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:3604
iterator begin() const
Definition: Sema/Lookup.h:276
DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, unsigned NumArgs, const TemplateArgument *Args, QualType Canon)
Definition: Type.cpp:2454
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5122
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1874
Declaration of a variable template.
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:5594
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:51
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:402
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
bool hasLValuePath() const
Definition: APValue.cpp:568
void setSpecializationKind(TemplateSpecializationKind TSK)
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:100
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:555
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:90
bool isBooleanType() const
Definition: Type.h:5609
A container of type source information.
Definition: Decl.h:61
unsigned getIndex() const
Definition: Type.h:3780
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:305
void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo)
static void StripImplicitInstantiation(NamedDecl *D)
Strips various properties off an implicit instantiation that has just been explicitly specialized...
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=None)
Definition: DeclFriend.cpp:27
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:8711
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
static bool CheckTemplatePartialSpecializationArgs(Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams, unsigned ExplicitArgs, SmallVectorImpl< TemplateArgument > &TemplateArgs)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
const TemplateArgumentLoc * getArgumentArray() const
Definition: TemplateBase.h:541
An identifier, stored as an IdentifierInfo*.
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:125
FriendDecl - Represents the declaration of a friend entity, which can be a function, a type, or a templated function or type.
Definition: DeclFriend.h:40
RAII object that enters a new expression evaluation context.
Definition: Sema.h:9238
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:699
CK_IntegralCast - A cast between integral types (other than to boolean).
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1608
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:46
Extra information about a function prototype.
Definition: Type.h:3067
AccessSpecifier getAccess() const
Definition: DeclBase.h:428
bool isCanonical() const
Definition: Type.h:5133
SourceLocation getLocation() const
Retrieve the location of the template argument.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:45
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1793
Represents a variable template specialization, which refers to a variable template with a given set o...
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:319
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
A namespace, stored as a NamespaceDecl*.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:48
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl< TemplateArgument > &Converted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
static Optional< unsigned > getExpandedPackSize(NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:3817
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3257
Defines the clang::Expr interface and subclasses for C++ expressions.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1739
Represents the builtin template declaration which is used to implement __make_integer_seq.
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier...
Definition: TypeLoc.h:485
The collection of all-type qualifiers we support.
Definition: Type.h:116
Information about a template-id annotation token.
PipeType - OpenCL20.
Definition: Type.h:5020
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:473
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1255
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2755
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:13679
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3166
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:95
static bool hasVisibleDefaultArgument(Sema &S, const ParmDecl *D, llvm::SmallVectorImpl< Module * > *Modules)
Scope * getTemplateParamParent()
Definition: Scope.h:250
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:942
QualType getElementType() const
Definition: Type.h:2700
DeclarationName getName() const
getName - Returns the embedded declaration name.
bool isConst() const
Definition: DeclCXX.h:1742
One of these records is kept for each identifier that is lexed.
Represents a class template specialization, which refers to a class template with a given set of temp...
iterator end() const
Definition: Sema/Lookup.h:277
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Sema/Lookup.h:57
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:622
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:233
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template.
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:3678
void replace(NamedDecl *D)
Replaces the current entry with the given one, preserving the access bits.
Definition: Sema/Lookup.h:601
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Represents a class type in Objective C.
Definition: Type.h:4557
AttributeList * getList() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1766
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:658
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:91
A C++ nested-name-specifier augmented with source location information.
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:411
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3165
static NamedDecl * isAcceptableTemplateName(ASTContext &Context, NamedDecl *Orig, bool AllowFunctionTemplates)
Determine whether the declaration found is acceptable as the name of a template and, if so, return that template declaration.
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:470
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:57
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2272
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1472
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1727
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
Decl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
bool isReferenceType() const
Definition: Type.h:5314
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:891
SourceLocation getLocation() const
Fetches the primary location of the argument.
Definition: TemplateBase.h:453
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:904
An operation on a type.
Definition: TypeVisitor.h:65
TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false)
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3538
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:925
bool isChar32Type() const
Definition: Type.cpp:1672
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:675
bool isTranslationUnit() const
Definition: DeclBase.h:1269
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:232
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:4348
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1788
TagKind getTagKind() const
Definition: Decl.h:2847
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:28
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:1962
CachedTokens Toks
Definition: Sema.h:9272
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:3872
A non-type template parameter, stored as an expression.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1744
unsigned size() const
Definition: DeclTemplate.h:91
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, const SmallVectorImpl< TemplateArgument > &Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void ClearStorageClassSpecs()
Definition: DeclSpec.h:455
The type of a non-type template parameter.
Definition: Sema.h:5991
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:472
SourceRange getSourceRange() const LLVM_READONLY
Fetches the full source range of the argument.
CK_NullToPointer - Null pointer constant to pointer, ObjC pointer, or block pointer.
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:497
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1191
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:1987
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:509
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Sema/Lookup.h:39
QualType getUnderlyingType() const
Definition: Type.h:3437
void setDefaultArgument(Expr *DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:102
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:391
T * getAttr() const
Definition: DeclBase.h:495
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, IdentifierInfo *Name)
CK_IntegralToBoolean - Integral to boolean.
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:874
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3078
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1416
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2351
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
param_type_range param_types() const
Definition: Type.h:3278
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:131
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:548
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1503
Represents the results of name lookup.
Definition: Sema/Lookup.h:30
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:580
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class...
Definition: Decl.cpp:3667
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1895
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:563
A convenient class for passing around template argument information.
Definition: TemplateBase.h:517
QualType getReturnType() const
Definition: Type.h:2977
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true)
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:608
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
KindType getKind() const
Determine what kind of template argument we have.
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3723
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3384
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:497
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:217
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1080
TypeDecl - Represents a declaration of a type.
Definition: Decl.h:2486
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2240
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:146
RecordDecl * getDecl() const
Definition: Type.h:3553
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2464
void setSpecializationKind(TemplateSpecializationKind TSK)
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:38
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
NullPointerValueKind
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:534
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1886
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:503
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:467
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1422
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:720
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &Converted)
Check that the given template arguments can be be provided to the given template, converting the argu...
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3034
A class that does preorder depth-first traversal on the entire Clang AST and visits each node...
static bool CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &Converted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:497
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Sema/Lookup.h:367
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:5865
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:496
detail::InMemoryDirectory::const_iterator I
Decl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed...
QualType getCanonicalTypeInternal() const
Definition: Type.h:1973
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getType() const
Definition: Decl.h:530
bool isInvalid() const
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:753
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:2685
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1034
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:2686
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Sema/Lookup.h:272
SourceRange getRange() const
Definition: DeclSpec.h:68
bool isDefined(const FunctionDecl *&Definition) const
isDefined - Returns true if the function is defined at all, including a deleted definition.
Definition: Decl.cpp:2485
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
EnumDecl * getDecl() const
Definition: Type.h:3576
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:5854
QualType getTemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon=QualType()) const
Represents a K&R-style 'int foo()' function, which has no information available about its arguments...
Definition: Type.h:3007
AnnotatingParser & P
TemplateName getUnderlying() const
Definition: TemplateName.h:336
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:168
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static Sema::TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, const TemplateArgument &Param, TemplateArgument Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5003
QualType getInjectedSpecializationType() const
Definition: Type.h:4158
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3178
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &Converted)
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1719
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:259
bool isNamespace() const
Definition: DeclBase.h:1277
TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x alias-declaration.
Definition: Decl.h:2618
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &Converted, CheckTemplateArgumentKind CTAK=CTAK_Specified)
Check that the given template argument corresponds to the given template parameter.
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Sema/Lookup.h:194
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1214
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2510
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:980
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
static TypeSourceInfo * SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, SmallVectorImpl< TemplateArgument > &Converted)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:454
Specifies that the expression should never be value-dependent.
Definition: Expr.h:680
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
ASTContext * Context
bool isEnum() const
Definition: Decl.h:2857
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2291
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:5836
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:188
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1903
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1881
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, const TemplateArgumentListInfo &Args) const
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:2627
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1716
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
int * Depth
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:155
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1855
QualType getPointeeType() const
Definition: Type.h:2268
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:521
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:5615
Expr - This represents one expression.
Definition: Expr.h:104
Defines the clang::LangOptions interface.
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs)
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Sema/Lookup.h:204
StringRef getName() const
Return the actual identifier string.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:99
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4202
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Sema/Lookup.h:344
StateNode * Previous
Declaration of a template type parameter.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Sema/Lookup.h:546
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:943
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4189
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:54
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, ClassTemplateDecl *PrevDecl)
Create a class template node.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion...
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:875
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Sema/Lookup.h:458
SourceLocation getLocation() const
Kind getKind() const
Definition: DeclBase.h:387
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:216
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3169
DeclContext * getDeclContext()
Definition: DeclBase.h:393
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2385
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:745
void NoteAllFoundTemplates(TemplateName Name)
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a C++ template name within the type system.
Definition: TemplateName.h:175
static DependentScopeDeclRefExpr * Create(const ASTContext &C, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:448
Represents the type decltype(expr) (C++11).
Definition: Type.h:3449
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given function template specialization.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
A namespace alias, stored as a NamespaceAliasDecl*.
void setLateTemplateParsed(bool ILT=true)
Definition: Decl.h:1753
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
bool isConstexprSpecified() const
Definition: DeclSpec.h:698
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:21
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:107
StorageClass
Storage classes.
Definition: Specifiers.h:198
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
A unary type transform, which is a type constructed from another.
Definition: Type.h:3490
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1751
bool isFunctionOrMethod() const
Definition: DeclBase.h:1249
Declaration of an alias template.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1200
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
Definition: TemplateBase.h:269
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:235
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, const TemplateArgument *Args, unsigned NumArgs, const TemplateArgumentListInfo &ArgInfos, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:42
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1654
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6601
Represents a GCC generic vector type.
Definition: Type.h:2724
void setLocation(SourceLocation L)
Definition: DeclBase.h:385
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2334
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:190
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3669
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:3988
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization)
ValueDecl * getDecl()
Definition: Expr.h:1007
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1239
QualType getElementType() const
Definition: Type.h:2748
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:144
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Definition: Decl.h:2874
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1797
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:450
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3285
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:1756
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:602
QualType getReplacementType() const
Gets the type that was substituted for the template parameter.
Definition: Type.h:3838
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:1794
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:95
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:473
bool isLValueOnePastTheEnd() const
Definition: APValue.cpp:558
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
bool isAmbiguous() const
Definition: Sema/Lookup.h:242
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:3377
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc)
void addAttr(Attr *A)
Definition: DeclBase.h:449
static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, bool OnlyDeduced, unsigned Level, llvm::SmallBitVector &Deduced)
Mark the template parameters that are used by the given type.
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter...
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
CanQualType OverloadTy
Definition: ASTContext.h:896
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1479
DeclContext * getEntity() const
Definition: Scope.h:310
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
ASTMatchFinder *const Finder
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1540
#define false
Definition: stdbool.h:33
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *Arg)
Determine whether the given template argument is a null pointer value of the appropriate type...
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:144
Kind
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5596
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:144
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1888
Represents the parsed form of a C++ template argument.
A stack object to be created when performing template instantiation.
Definition: Sema.h:6687
TypeSourceInfo * getDefaultArgumentInfo() const
Retrieves the default argument's source information, if any.
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
Encodes a location in the source.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5089
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3570
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:262
QualType getElementType() const
Definition: Type.h:2099
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1522
Represents typeof(type), a GCC extension.
Definition: Type.h:3425
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:4766
An overloaded operator name, e.g., operator+.
Definition: DeclSpec.h:885
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &Converted)
Checks whether the given template argument is the address of an object or function according to C++ [...
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:216
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1731
bool isValid() const
Return true if this is a valid SourceLocation object.
void setExternLoc(SourceLocation Loc)
Sets the location of the extern keyword.
static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS)
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2644
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc)
Build the type that describes a C++ typename specifier, e.g., "typename T::type". ...
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply...
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:311
CK_NullToMemberPointer - Null pointer constant to member pointer.
bool isValid() const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ASTContext & getASTContext() const
Definition: Sema.h:1048
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:92
ValueKind getKind() const
Definition: APValue.h:180
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3004
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1701
unsigned getDepth() const
Retrieve the depth of the template parameter.
void print(const PrintingPolicy &Policy, raw_ostream &Out) const
Print this template argument to the given output stream.
SourceLocation getNameLoc() const
Definition: TypeLoc.h:493
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void set(Decl *Spec, DeductionFailureInfo Info)
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Expr * getDefaultArgument() const
Retrieve the default argument, if any.
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Sema/Lookup.h:52
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template...
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:699
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition: Scope.h:362
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:77
bool Matches
void setPointOfInstantiation(SourceLocation Loc)
A class for iterating through a result set and possibly filtering out results.
Definition: Sema/Lookup.h:557
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1843
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2712
SourceLocation getBegin() const
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:164
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
No entity found met the criteria.
Definition: Sema/Lookup.h:34
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:156
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:141
bool isFileContext() const
Definition: DeclBase.h:1265
PtrTy get() const
Definition: Ownership.h:74
A template type parameter, stored as a type.
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization, returns the templated static data member from which it was instantiated.
Definition: Decl.cpp:2255
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
Attr * clone(ASTContext &C) const
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:69
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:557
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:245
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:4128
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1235
QualType getPointeeType() const
Definition: Type.h:2161
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:2706
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Represents a pack expansion of types.
Definition: Type.h:4471
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
A POD class for pairing a NamedDecl* with an access specifier.
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1451
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply<U>...
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1743
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template...
Definition: Decl.cpp:2300
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Decl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e.g.
QualType getType() const
Definition: Expr.h:125
Represents a template argument.
Definition: TemplateBase.h:40
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1243
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:238
TagTypeKind
The kind of a tag type.
Definition: Type.h:4174
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3164
The name does not refer to a template.
Definition: TemplateKinds.h:23
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument...
void setMemberSpecialization()
Note that this member template is a specialization.
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void removeDefaultArgument()
Removes the default argument of this template parameter.
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3025
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1121
CanQualType NullPtrTy
Definition: ASTContext.h:895
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:561
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Sema/Lookup.h:214
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
bool isDependent() const
Determines whether this is a dependent template name.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:369
SourceLocation getLocStart() const LLVM_READONLY
Definition: TypeLoc.h:130
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:63
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition: Decl.cpp:3660
CXXScopeSpec SS
The nested-name-specifier that precedes the template name.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
TemplateName getCanonicalTemplateName(TemplateName Name) const
Retrieves the "canonical" template name that refers to a given template.
bool isInvalidDecl() const
Definition: DeclBase.h:509
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:104
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:75
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:152
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:514
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo &TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization...
Definition: Decl.cpp:3225
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:3483
std::string getAsString(ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:545
bool isThisDeclarationADefinition() const
isThisDeclarationADefinition - Returns whether this specific declaration of the function is also a de...
Definition: Decl.h:1725
EnumDecl - Represents an enum.
Definition: Decl.h:2930
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2369
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:138
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set...
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Sema/Lookup.h:249
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1946
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
A type that was preceded by the 'template' keyword, stored as a Type*.
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration...
Definition: DeclBase.h:939
bool isWideCharType() const
Definition: Type.cpp:1659
unsigned getDepth() const
Get the nesting depth of the template parameter.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5255
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1807
Represents a pointer to an Objective C object.
Definition: Type.h:4821
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:127
Pointer to a block type.
Definition: Type.h:2254
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args, unsigned NumArgs, const TemplateArgumentListInfo &ArgInfos)
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
Name lookup found a single declaration that met the criteria.
Definition: Sema/Lookup.h:43
bool empty() const
Return true if no decls were found.
Definition: Sema/Lookup.h:280
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:573
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:534
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3544
Complex values, per C99 6.2.5p11.
Definition: Type.h:2087
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:421
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:3584
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args, unsigned NumArgs)
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3285
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:5762
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:532
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:148
static SourceRange findTemplateParameter(unsigned Depth, Expr *E)
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3268
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:1780
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:294
bool isNull() const
Determine whether this template name is NULL.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:607
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2323
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, bool NeedDefinition, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool isFunctionType() const
Definition: Type.h:5302
ExtVectorType - Extended vector type.
Definition: Type.h:2784
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2287
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1495
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1522
bool isInvalid() const
Determine whether the given template argument is invalid.
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:978
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, AttributeList *Attr)
The template argument is a type.
Definition: TemplateBase.h:48
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:254
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:78
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:379
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
bool isInlineSpecified() const
Definition: DeclSpec.h:552
The template argument is actually a parameter pack.
Definition: TemplateBase.h:72
A template-id, e.g., f<int>.
Definition: DeclSpec.h:897
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:986
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2354
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this variable template specialization is actually an instantiation of the given variable te...
QualType getPointeeType() const
Definition: Type.h:2308
This is a scope that can contain a declaration.
Definition: Scope.h:57
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:1951
A template argument list.
Definition: DeclTemplate.h:172
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
const Type * getClass() const
Definition: Type.h:2402
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
getCXXLiteralOperatorName - Get the name of the literal operator function with II as the identifier...
TemplateNameKind ActOnDependentTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template)
Form a dependent template name.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:335
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:360
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:1957
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5169
const LValueBase getLValueBase() const
Definition: APValue.cpp:553
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
BoundNodesTreeBuilder *const Builder
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
A user-defined literal name, e.g., operator "" _i.
Definition: DeclSpec.h:889
Decl * D
The template function declaration to be late parsed.
Definition: Sema.h:9274
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:60
Represents a C array with an unspecified size.
Definition: Type.h:2530
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:437
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member...
Definition: Decl.cpp:2059
void setConstexpr(bool IC)
Definition: Decl.h:1795
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition: Sema.h:776
static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned NumArgs, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:492
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:92
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
Location information for a TemplateArgument.
Definition: TemplateBase.h:362
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:307
The "enum" keyword.
Definition: Type.h:4184
Declaration of a class template.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:853
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:115
This class is used for builtin types like 'int'.
Definition: Type.h:2011
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:355
LookupResultKind getResultKind() const
Definition: Sema/Lookup.h:262
bool isArrayType() const
Definition: Type.h:5344
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
Defines the clang::TargetInfo interface.
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:4498
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1316
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1465
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
ExprResult ExprError()
Definition: Ownership.h:267
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:772
CanQualType IntTy
Definition: ASTContext.h:889
bool isRecord() const
Definition: DeclBase.h:1273
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization)
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
CK_NoOp - A conversion which does not affect the type other than (possibly) adding qualifiers...
bool hasEllipsis() const
Definition: DeclSpec.h:2211
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:922
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:400
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
NamedDecl * getMostRecentDecl()
Definition: Decl.h:332
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:132
QualType getElementType() const
Definition: Type.h:2458
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5164
void setMemberSpecialization()
Note that this member template is a specialization.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Diagnose an arity mismatch in the.
Contains a late templated function.
Definition: Sema.h:9271
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Sema/Lookup.h:523
AttributeList * getNext() const
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:106
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
StringRef getKindName() const
Definition: Decl.h:2843
Wrapper for template type parameters.
Definition: TypeLoc.h:688
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:6775
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:180
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:384
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:245
ASTContext & Context
Definition: Sema.h:295
NamedDecl - This represents a decl with a name.
Definition: Decl.h:145
bool isInvalidType() const
Definition: DeclSpec.h:2200
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:455
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization, retrieves the function from which it was instantiated.
Definition: Decl.cpp:3041
void dropAttr()
Definition: DeclBase.h:471
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:423
A template template argument, stored as a template name.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2575
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1486
No keyword precedes the qualified type name.
Definition: Type.h:4204
APSInt & getInt()
Definition: APValue.h:200
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:642
void setTypeAsWritten(TypeSourceInfo *T)
Sets the type of this specialization as it was written by the user.
unsigned NumArgs
NumArgs - The number of template arguments.
The global specifier '::'. There is no stored value.
void setType(QualType newType)
Definition: Decl.h:531
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:464
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:134
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2480
Defines enum values for all the target-independent builtin functions.
Declaration of a template function.
Definition: DeclTemplate.h:830
void clear()
Clears out any current state.
Definition: Sema/Lookup.h:495
bool IsInsideALocalClassWithinATemplateFunction()
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1730
Attr - This represents one attribute.
Definition: Attr.h:44
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:741
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:2764
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1712
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:72
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity)
Perform substitution on the type T with a given set of template arguments.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5116
bool isLValue() const
Definition: APValue.h:186
bool isPointerType() const
Definition: Type.h:5305
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
getCXXOperatorName - Get the name of the overloadable C++ operator corresponding to Op...
A RAII object to temporarily push a declaration context.
Definition: Sema.h:601
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:130
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1551
QualType getDeducedType() const
Get the type deduced for this auto type, or null if it's either not been deduced or was deduced to a ...
Definition: Type.h:3945