clang  10.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===/
7 //
8 // This file implements C++ template instantiation.
9 //
10 //===----------------------------------------------------------------------===/
11 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
21 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/Stack.h"
24 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Template.h"
30 #include "clang/Sema/SemaConcept.h"
31 #include "llvm/Support/TimeProfiler.h"
32 
33 using namespace clang;
34 using namespace sema;
35 
36 //===----------------------------------------------------------------------===/
37 // Template Instantiation Support
38 //===----------------------------------------------------------------------===/
39 
40 /// Retrieve the template argument list(s) that should be used to
41 /// instantiate the definition of the given declaration.
42 ///
43 /// \param D the declaration for which we are computing template instantiation
44 /// arguments.
45 ///
46 /// \param Innermost if non-NULL, the innermost template argument list.
47 ///
48 /// \param RelativeToPrimary true if we should get the template
49 /// arguments relative to the primary template, even when we're
50 /// dealing with a specialization. This is only relevant for function
51 /// template specializations.
52 ///
53 /// \param Pattern If non-NULL, indicates the pattern from which we will be
54 /// instantiating the definition of the given declaration, \p D. This is
55 /// used to determine the proper set of template instantiation arguments for
56 /// friend function template specializations.
59  const TemplateArgumentList *Innermost,
60  bool RelativeToPrimary,
61  const FunctionDecl *Pattern) {
62  // Accumulate the set of template argument lists in this structure.
64 
65  if (Innermost)
66  Result.addOuterTemplateArguments(Innermost);
67 
68  DeclContext *Ctx = dyn_cast<DeclContext>(D);
69  if (!Ctx) {
70  Ctx = D->getDeclContext();
71 
72  // Add template arguments from a variable template instantiation. For a
73  // class-scope explicit specialization, there are no template arguments
74  // at this level, but there may be enclosing template arguments.
76  dyn_cast<VarTemplateSpecializationDecl>(D);
77  if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
78  // We're done when we hit an explicit specialization.
80  !isa<VarTemplatePartialSpecializationDecl>(Spec))
81  return Result;
82 
84 
85  // If this variable template specialization was instantiated from a
86  // specialized member that is a variable template, we're done.
87  assert(Spec->getSpecializedTemplate() && "No variable template?");
88  llvm::PointerUnion<VarTemplateDecl*,
92  Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
93  if (Partial->isMemberSpecialization())
94  return Result;
95  } else {
96  VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
97  if (Tmpl->isMemberSpecialization())
98  return Result;
99  }
100  }
101 
102  // If we have a template template parameter with translation unit context,
103  // then we're performing substitution into a default template argument of
104  // this template template parameter before we've constructed the template
105  // that will own this template template parameter. In this case, we
106  // use empty template parameter lists for all of the outer templates
107  // to avoid performing any substitutions.
108  if (Ctx->isTranslationUnit()) {
109  if (TemplateTemplateParmDecl *TTP
110  = dyn_cast<TemplateTemplateParmDecl>(D)) {
111  for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
112  Result.addOuterTemplateArguments(None);
113  return Result;
114  }
115  }
116  }
117 
118  while (!Ctx->isFileContext()) {
119  // Add template arguments from a class template instantiation.
121  = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
122  if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
123  // We're done when we hit an explicit specialization.
125  !isa<ClassTemplatePartialSpecializationDecl>(Spec))
126  break;
127 
129 
130  // If this class template specialization was instantiated from a
131  // specialized member that is a class template, we're done.
132  assert(Spec->getSpecializedTemplate() && "No class template?");
134  break;
135  }
136  // Add template arguments from a function template specialization.
137  else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
138  if (!RelativeToPrimary &&
139  Function->getTemplateSpecializationKindForInstantiation() ==
141  break;
142 
143  if (const TemplateArgumentList *TemplateArgs
144  = Function->getTemplateSpecializationArgs()) {
145  // Add the template arguments for this specialization.
146  Result.addOuterTemplateArguments(TemplateArgs);
147 
148  // If this function was instantiated from a specialized member that is
149  // a function template, we're done.
150  assert(Function->getPrimaryTemplate() && "No function template?");
151  if (Function->getPrimaryTemplate()->isMemberSpecialization())
152  break;
153 
154  // If this function is a generic lambda specialization, we are done.
156  break;
157 
158  } else if (FunctionTemplateDecl *FunTmpl
159  = Function->getDescribedFunctionTemplate()) {
160  // Add the "injected" template arguments.
161  Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
162  }
163 
164  // If this is a friend declaration and it declares an entity at
165  // namespace scope, take arguments from its lexical parent
166  // instead of its semantic parent, unless of course the pattern we're
167  // instantiating actually comes from the file's context!
168  if (Function->getFriendObjectKind() &&
169  Function->getDeclContext()->isFileContext() &&
170  (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
171  Ctx = Function->getLexicalDeclContext();
172  RelativeToPrimary = false;
173  continue;
174  }
175  } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
176  if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
177  QualType T = ClassTemplate->getInjectedClassNameSpecialization();
178  const TemplateSpecializationType *TST =
179  cast<TemplateSpecializationType>(Context.getCanonicalType(T));
181  llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
182  if (ClassTemplate->isMemberSpecialization())
183  break;
184  }
185  }
186 
187  Ctx = Ctx->getParent();
188  RelativeToPrimary = false;
189  }
190 
191  return Result;
192 }
193 
195  switch (Kind) {
196  case TemplateInstantiation:
197  case ExceptionSpecInstantiation:
198  case DefaultTemplateArgumentInstantiation:
199  case DefaultFunctionArgumentInstantiation:
200  case ExplicitTemplateArgumentSubstitution:
201  case DeducedTemplateArgumentSubstitution:
202  case PriorTemplateArgumentSubstitution:
203  case ConstraintsCheck:
204  case NestedRequirementConstraintsCheck:
205  return true;
206 
207  case RequirementInstantiation:
208  case DefaultTemplateArgumentChecking:
209  case DeclaringSpecialMember:
210  case DeclaringImplicitEqualityComparison:
211  case DefiningSynthesizedFunction:
212  case ExceptionSpecEvaluation:
213  case ConstraintSubstitution:
214  case ParameterMappingSubstitution:
215  case ConstraintNormalization:
216  case RewritingOperatorAsSpaceship:
217  return false;
218 
219  // This function should never be called when Kind's value is Memoization.
220  case Memoization:
221  break;
222  }
223 
224  llvm_unreachable("Invalid SynthesisKind!");
225 }
226 
229  SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
230  Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
231  sema::TemplateDeductionInfo *DeductionInfo)
232  : SemaRef(SemaRef) {
233  // Don't allow further instantiation if a fatal error and an uncompilable
234  // error have occurred. Any diagnostics we might have raised will not be
235  // visible, and we do not need to construct a correct AST.
236  if (SemaRef.Diags.hasFatalErrorOccurred() &&
238  Invalid = true;
239  return;
240  }
241  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
242  if (!Invalid) {
244  Inst.Kind = Kind;
245  Inst.PointOfInstantiation = PointOfInstantiation;
246  Inst.Entity = Entity;
247  Inst.Template = Template;
248  Inst.TemplateArgs = TemplateArgs.data();
249  Inst.NumTemplateArgs = TemplateArgs.size();
250  Inst.DeductionInfo = DeductionInfo;
251  Inst.InstantiationRange = InstantiationRange;
252  SemaRef.pushCodeSynthesisContext(Inst);
253 
254  AlreadyInstantiating = !Inst.Entity ? false :
256  .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
257  .second;
258  atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
259  }
260 }
261 
263  Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
264  SourceRange InstantiationRange)
265  : InstantiatingTemplate(SemaRef,
266  CodeSynthesisContext::TemplateInstantiation,
267  PointOfInstantiation, InstantiationRange, Entity) {}
268 
270  Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
271  ExceptionSpecification, SourceRange InstantiationRange)
273  SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
274  PointOfInstantiation, InstantiationRange, Entity) {}
275 
277  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
278  TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
279  SourceRange InstantiationRange)
281  SemaRef,
282  CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
283  PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
284  Template, TemplateArgs) {}
285 
287  Sema &SemaRef, SourceLocation PointOfInstantiation,
288  FunctionTemplateDecl *FunctionTemplate,
289  ArrayRef<TemplateArgument> TemplateArgs,
291  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
292  : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
293  InstantiationRange, FunctionTemplate, nullptr,
294  TemplateArgs, &DeductionInfo) {
295  assert(
298 }
299 
301  Sema &SemaRef, SourceLocation PointOfInstantiation,
302  TemplateDecl *Template,
303  ArrayRef<TemplateArgument> TemplateArgs,
304  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
306  SemaRef,
307  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
308  PointOfInstantiation, InstantiationRange, Template, nullptr,
309  TemplateArgs, &DeductionInfo) {}
310 
312  Sema &SemaRef, SourceLocation PointOfInstantiation,
314  ArrayRef<TemplateArgument> TemplateArgs,
315  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
317  SemaRef,
318  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
319  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
320  TemplateArgs, &DeductionInfo) {}
321 
323  Sema &SemaRef, SourceLocation PointOfInstantiation,
325  ArrayRef<TemplateArgument> TemplateArgs,
326  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
328  SemaRef,
329  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
330  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
331  TemplateArgs, &DeductionInfo) {}
332 
334  Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
335  ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
337  SemaRef,
338  CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
339  PointOfInstantiation, InstantiationRange, Param, nullptr,
340  TemplateArgs) {}
341 
343  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
345  SourceRange InstantiationRange)
347  SemaRef,
348  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
349  PointOfInstantiation, InstantiationRange, Param, Template,
350  TemplateArgs) {}
351 
353  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
355  SourceRange InstantiationRange)
357  SemaRef,
358  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
359  PointOfInstantiation, InstantiationRange, Param, Template,
360  TemplateArgs) {}
361 
363  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
364  NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
365  SourceRange InstantiationRange)
367  SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
368  PointOfInstantiation, InstantiationRange, Param, Template,
369  TemplateArgs) {}
370 
372  Sema &SemaRef, SourceLocation PointOfInstantiation,
374  SourceRange InstantiationRange)
376  SemaRef, CodeSynthesisContext::RequirementInstantiation,
377  PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
378  /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {}
379 
380 
382  Sema &SemaRef, SourceLocation PointOfInstantiation,
384  SourceRange InstantiationRange)
386  SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
387  PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
388  /*Template=*/nullptr, /*TemplateArgs=*/None) {}
389 
390 
392  Sema &SemaRef, SourceLocation PointOfInstantiation,
393  ConstraintsCheck, NamedDecl *Template,
394  ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
397  PointOfInstantiation, InstantiationRange, Template, nullptr,
398  TemplateArgs) {}
399 
401  Sema &SemaRef, SourceLocation PointOfInstantiation,
403  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
406  PointOfInstantiation, InstantiationRange, Template, nullptr,
407  {}, &DeductionInfo) {}
408 
410  Sema &SemaRef, SourceLocation PointOfInstantiation,
412  SourceRange InstantiationRange)
415  PointOfInstantiation, InstantiationRange, Template) {}
416 
418  Sema &SemaRef, SourceLocation PointOfInstantiation,
420  SourceRange InstantiationRange)
423  PointOfInstantiation, InstantiationRange, Template) {}
424 
428 
429  CodeSynthesisContexts.push_back(Ctx);
430 
431  if (!Ctx.isInstantiationRecord())
433 
434  // Check to see if we're low on stack space. We can't do anything about this
435  // from here, but we can at least warn the user.
438 }
439 
441  auto &Active = CodeSynthesisContexts.back();
442  if (!Active.isInstantiationRecord()) {
443  assert(NonInstantiationEntries > 0);
445  }
446 
447  InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
448 
449  // Name lookup no longer looks in this template's defining module.
450  assert(CodeSynthesisContexts.size() >=
452  "forgot to remove a lookup module for a template instantiation");
453  if (CodeSynthesisContexts.size() ==
456  LookupModulesCache.erase(M);
458  }
459 
460  // If we've left the code synthesis context for the current context stack,
461  // stop remembering that we've emitted that stack.
462  if (CodeSynthesisContexts.size() ==
465 
466  CodeSynthesisContexts.pop_back();
467 }
468 
470  if (!Invalid) {
471  if (!AlreadyInstantiating) {
472  auto &Active = SemaRef.CodeSynthesisContexts.back();
473  if (Active.Entity)
474  SemaRef.InstantiatingSpecializations.erase(
475  std::make_pair(Active.Entity, Active.Kind));
476  }
477 
478  atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
479  SemaRef.CodeSynthesisContexts.back());
480 
481  SemaRef.popCodeSynthesisContext();
482  Invalid = true;
483  }
484 }
485 
486 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
487  SourceLocation PointOfInstantiation,
488  SourceRange InstantiationRange) {
489  assert(SemaRef.NonInstantiationEntries <=
490  SemaRef.CodeSynthesisContexts.size());
491  if ((SemaRef.CodeSynthesisContexts.size() -
492  SemaRef.NonInstantiationEntries)
493  <= SemaRef.getLangOpts().InstantiationDepth)
494  return false;
495 
496  SemaRef.Diag(PointOfInstantiation,
497  diag::err_template_recursion_depth_exceeded)
498  << SemaRef.getLangOpts().InstantiationDepth
499  << InstantiationRange;
500  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
501  << SemaRef.getLangOpts().InstantiationDepth;
502  return true;
503 }
504 
505 /// Prints the current instantiation stack through a series of
506 /// notes.
508  // Determine which template instantiations to skip, if any.
509  unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
510  unsigned Limit = Diags.getTemplateBacktraceLimit();
511  if (Limit && Limit < CodeSynthesisContexts.size()) {
512  SkipStart = Limit / 2 + Limit % 2;
513  SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
514  }
515 
516  // FIXME: In all of these cases, we need to show the template arguments
517  unsigned InstantiationIdx = 0;
519  Active = CodeSynthesisContexts.rbegin(),
520  ActiveEnd = CodeSynthesisContexts.rend();
521  Active != ActiveEnd;
522  ++Active, ++InstantiationIdx) {
523  // Skip this instantiation?
524  if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
525  if (InstantiationIdx == SkipStart) {
526  // Note that we're skipping instantiations.
527  Diags.Report(Active->PointOfInstantiation,
528  diag::note_instantiation_contexts_suppressed)
529  << unsigned(CodeSynthesisContexts.size() - Limit);
530  }
531  continue;
532  }
533 
534  switch (Active->Kind) {
536  Decl *D = Active->Entity;
537  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
538  unsigned DiagID = diag::note_template_member_class_here;
539  if (isa<ClassTemplateSpecializationDecl>(Record))
540  DiagID = diag::note_template_class_instantiation_here;
541  Diags.Report(Active->PointOfInstantiation, DiagID)
542  << Record << Active->InstantiationRange;
543  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
544  unsigned DiagID;
545  if (Function->getPrimaryTemplate())
546  DiagID = diag::note_function_template_spec_here;
547  else
548  DiagID = diag::note_template_member_function_here;
549  Diags.Report(Active->PointOfInstantiation, DiagID)
550  << Function
551  << Active->InstantiationRange;
552  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
553  Diags.Report(Active->PointOfInstantiation,
554  VD->isStaticDataMember()?
555  diag::note_template_static_data_member_def_here
556  : diag::note_template_variable_def_here)
557  << VD
558  << Active->InstantiationRange;
559  } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
560  Diags.Report(Active->PointOfInstantiation,
561  diag::note_template_enum_def_here)
562  << ED
563  << Active->InstantiationRange;
564  } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
565  Diags.Report(Active->PointOfInstantiation,
566  diag::note_template_nsdmi_here)
567  << FD << Active->InstantiationRange;
568  } else {
569  Diags.Report(Active->PointOfInstantiation,
570  diag::note_template_type_alias_instantiation_here)
571  << cast<TypeAliasTemplateDecl>(D)
572  << Active->InstantiationRange;
573  }
574  break;
575  }
576 
578  TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
579  SmallVector<char, 128> TemplateArgsStr;
580  llvm::raw_svector_ostream OS(TemplateArgsStr);
581  Template->printName(OS);
582  printTemplateArgumentList(OS, Active->template_arguments(),
584  Diags.Report(Active->PointOfInstantiation,
585  diag::note_default_arg_instantiation_here)
586  << OS.str()
587  << Active->InstantiationRange;
588  break;
589  }
590 
592  FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
593  Diags.Report(Active->PointOfInstantiation,
594  diag::note_explicit_template_arg_substitution_here)
595  << FnTmpl
597  Active->TemplateArgs,
598  Active->NumTemplateArgs)
599  << Active->InstantiationRange;
600  break;
601  }
602 
604  if (FunctionTemplateDecl *FnTmpl =
605  dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
606  Diags.Report(Active->PointOfInstantiation,
607  diag::note_function_template_deduction_instantiation_here)
608  << FnTmpl
609  << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
610  Active->TemplateArgs,
611  Active->NumTemplateArgs)
612  << Active->InstantiationRange;
613  } else {
614  bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
615  isa<VarTemplateSpecializationDecl>(Active->Entity);
616  bool IsTemplate = false;
617  TemplateParameterList *Params;
618  if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
619  IsTemplate = true;
620  Params = D->getTemplateParameters();
621  } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
622  Active->Entity)) {
623  Params = D->getTemplateParameters();
624  } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
625  Active->Entity)) {
626  Params = D->getTemplateParameters();
627  } else {
628  llvm_unreachable("unexpected template kind");
629  }
630 
631  Diags.Report(Active->PointOfInstantiation,
632  diag::note_deduced_template_arg_substitution_here)
633  << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
634  << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
635  Active->NumTemplateArgs)
636  << Active->InstantiationRange;
637  }
638  break;
639  }
640 
642  ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
643  FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
644 
645  SmallVector<char, 128> TemplateArgsStr;
646  llvm::raw_svector_ostream OS(TemplateArgsStr);
647  FD->printName(OS);
648  printTemplateArgumentList(OS, Active->template_arguments(),
650  Diags.Report(Active->PointOfInstantiation,
651  diag::note_default_function_arg_instantiation_here)
652  << OS.str()
653  << Active->InstantiationRange;
654  break;
655  }
656 
658  NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
659  std::string Name;
660  if (!Parm->getName().empty())
661  Name = std::string(" '") + Parm->getName().str() + "'";
662 
663  TemplateParameterList *TemplateParams = nullptr;
664  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
665  TemplateParams = Template->getTemplateParameters();
666  else
667  TemplateParams =
668  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
669  ->getTemplateParameters();
670  Diags.Report(Active->PointOfInstantiation,
671  diag::note_prior_template_arg_substitution)
672  << isa<TemplateTemplateParmDecl>(Parm)
673  << Name
674  << getTemplateArgumentBindingsText(TemplateParams,
675  Active->TemplateArgs,
676  Active->NumTemplateArgs)
677  << Active->InstantiationRange;
678  break;
679  }
680 
682  TemplateParameterList *TemplateParams = nullptr;
683  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
684  TemplateParams = Template->getTemplateParameters();
685  else
686  TemplateParams =
687  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
688  ->getTemplateParameters();
689 
690  Diags.Report(Active->PointOfInstantiation,
691  diag::note_template_default_arg_checking)
692  << getTemplateArgumentBindingsText(TemplateParams,
693  Active->TemplateArgs,
694  Active->NumTemplateArgs)
695  << Active->InstantiationRange;
696  break;
697  }
698 
700  Diags.Report(Active->PointOfInstantiation,
701  diag::note_evaluating_exception_spec_here)
702  << cast<FunctionDecl>(Active->Entity);
703  break;
704 
706  Diags.Report(Active->PointOfInstantiation,
707  diag::note_template_exception_spec_instantiation_here)
708  << cast<FunctionDecl>(Active->Entity)
709  << Active->InstantiationRange;
710  break;
711 
713  Diags.Report(Active->PointOfInstantiation,
714  diag::note_template_requirement_instantiation_here)
715  << Active->InstantiationRange;
716  break;
717 
719  Diags.Report(Active->PointOfInstantiation,
720  diag::note_nested_requirement_here)
721  << Active->InstantiationRange;
722  break;
723 
725  Diags.Report(Active->PointOfInstantiation,
726  diag::note_in_declaration_of_implicit_special_member)
727  << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
728  break;
729 
731  Diags.Report(Active->Entity->getLocation(),
732  diag::note_in_declaration_of_implicit_equality_comparison);
733  break;
734 
736  // FIXME: For synthesized functions that are not defaulted,
737  // produce a note.
738  auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
741  if (DFK.isSpecialMember()) {
742  auto *MD = cast<CXXMethodDecl>(FD);
743  Diags.Report(Active->PointOfInstantiation,
744  diag::note_member_synthesized_at)
745  << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
746  << Context.getTagDeclType(MD->getParent());
747  } else if (DFK.isComparison()) {
748  Diags.Report(Active->PointOfInstantiation,
749  diag::note_comparison_synthesized_at)
750  << (int)DFK.asComparison()
752  cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
753  }
754  break;
755  }
756 
758  Diags.Report(Active->Entity->getLocation(),
759  diag::note_rewriting_operator_as_spaceship);
760  break;
761 
763  break;
764 
766  unsigned DiagID = 0;
767  if (!Active->Entity) {
768  Diags.Report(Active->PointOfInstantiation,
769  diag::note_nested_requirement_here)
770  << Active->InstantiationRange;
771  break;
772  }
773  if (isa<ConceptDecl>(Active->Entity))
774  DiagID = diag::note_concept_specialization_here;
775  else if (isa<TemplateDecl>(Active->Entity))
776  DiagID = diag::note_checking_constraints_for_template_id_here;
777  else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
778  DiagID = diag::note_checking_constraints_for_var_spec_id_here;
779  else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
780  DiagID = diag::note_checking_constraints_for_class_spec_id_here;
781  else {
782  assert(isa<FunctionDecl>(Active->Entity));
783  DiagID = diag::note_checking_constraints_for_function_here;
784  }
785  SmallVector<char, 128> TemplateArgsStr;
786  llvm::raw_svector_ostream OS(TemplateArgsStr);
787  cast<NamedDecl>(Active->Entity)->printName(OS);
788  if (!isa<FunctionDecl>(Active->Entity))
789  printTemplateArgumentList(OS, Active->template_arguments(),
791  Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
792  << Active->InstantiationRange;
793  break;
794  }
796  Diags.Report(Active->PointOfInstantiation,
797  diag::note_constraint_substitution_here)
798  << Active->InstantiationRange;
799  break;
801  Diags.Report(Active->PointOfInstantiation,
802  diag::note_constraint_normalization_here)
803  << cast<NamedDecl>(Active->Entity)->getName()
804  << Active->InstantiationRange;
805  break;
807  Diags.Report(Active->PointOfInstantiation,
808  diag::note_parameter_mapping_substitution_here)
809  << Active->InstantiationRange;
810  break;
811  }
812  }
813 }
814 
817  return Optional<TemplateDeductionInfo *>(nullptr);
818 
820  Active = CodeSynthesisContexts.rbegin(),
821  ActiveEnd = CodeSynthesisContexts.rend();
822  Active != ActiveEnd;
823  ++Active)
824  {
825  switch (Active->Kind) {
827  // An instantiation of an alias template may or may not be a SFINAE
828  // context, depending on what else is on the stack.
829  if (isa<TypeAliasTemplateDecl>(Active->Entity))
830  break;
831  LLVM_FALLTHROUGH;
838  // This is a template instantiation, so there is no SFINAE.
839  return None;
840 
844  // A default template argument instantiation and substitution into
845  // template parameters with arguments for prior parameters may or may
846  // not be a SFINAE context; look further up the stack.
847  break;
848 
853  // We're either substituting explicitly-specified template arguments,
854  // deduced template arguments, a constraint expression or a requirement
855  // in a requires expression, so SFINAE applies.
856  assert(Active->DeductionInfo && "Missing deduction info pointer");
857  return Active->DeductionInfo;
858 
863  // This happens in a context unrelated to template instantiation, so
864  // there is no SFINAE.
865  return None;
866 
868  // FIXME: This should not be treated as a SFINAE context, because
869  // we will cache an incorrect exception specification. However, clang
870  // bootstrap relies this! See PR31692.
871  break;
872 
874  break;
875  }
876 
877  // The inner context was transparent for SFINAE. If it occurred within a
878  // non-instantiation SFINAE context, then SFINAE applies.
879  if (Active->SavedInNonInstantiationSFINAEContext)
880  return Optional<TemplateDeductionInfo *>(nullptr);
881  }
882 
883  return None;
884 }
885 
886 //===----------------------------------------------------------------------===/
887 // Template Instantiation for Types
888 //===----------------------------------------------------------------------===/
889 namespace {
890  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
891  const MultiLevelTemplateArgumentList &TemplateArgs;
892  SourceLocation Loc;
893  DeclarationName Entity;
894 
895  public:
896  typedef TreeTransform<TemplateInstantiator> inherited;
897 
898  TemplateInstantiator(Sema &SemaRef,
899  const MultiLevelTemplateArgumentList &TemplateArgs,
900  SourceLocation Loc,
901  DeclarationName Entity)
902  : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
903  Entity(Entity) { }
904 
905  /// Determine whether the given type \p T has already been
906  /// transformed.
907  ///
908  /// For the purposes of template instantiation, a type has already been
909  /// transformed if it is NULL or if it is not dependent.
910  bool AlreadyTransformed(QualType T);
911 
912  /// Returns the location of the entity being instantiated, if known.
913  SourceLocation getBaseLocation() { return Loc; }
914 
915  /// Returns the name of the entity being instantiated, if any.
916  DeclarationName getBaseEntity() { return Entity; }
917 
918  /// Sets the "base" location and entity when that
919  /// information is known based on another transformation.
920  void setBase(SourceLocation Loc, DeclarationName Entity) {
921  this->Loc = Loc;
922  this->Entity = Entity;
923  }
924 
925  bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
926  SourceRange PatternRange,
928  bool &ShouldExpand, bool &RetainExpansion,
929  Optional<unsigned> &NumExpansions) {
930  return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
931  PatternRange, Unexpanded,
932  TemplateArgs,
933  ShouldExpand,
934  RetainExpansion,
935  NumExpansions);
936  }
937 
938  void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
940  }
941 
942  TemplateArgument ForgetPartiallySubstitutedPack() {
944  if (NamedDecl *PartialPack
946  MultiLevelTemplateArgumentList &TemplateArgs
947  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
948  unsigned Depth, Index;
949  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
950  if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
951  Result = TemplateArgs(Depth, Index);
952  TemplateArgs.setArgument(Depth, Index, TemplateArgument());
953  }
954  }
955 
956  return Result;
957  }
958 
959  void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
960  if (Arg.isNull())
961  return;
962 
963  if (NamedDecl *PartialPack
965  MultiLevelTemplateArgumentList &TemplateArgs
966  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
967  unsigned Depth, Index;
968  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
969  TemplateArgs.setArgument(Depth, Index, Arg);
970  }
971  }
972 
973  /// Transform the given declaration by instantiating a reference to
974  /// this declaration.
975  Decl *TransformDecl(SourceLocation Loc, Decl *D);
976 
977  void transformAttrs(Decl *Old, Decl *New) {
978  SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
979  }
980 
981  void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
982  if (Old->isParameterPack()) {
984  for (auto *New : NewDecls)
986  Old, cast<VarDecl>(New));
987  return;
988  }
989 
990  assert(NewDecls.size() == 1 &&
991  "should only have multiple expansions for a pack");
992  Decl *New = NewDecls.front();
993 
994  // If we've instantiated the call operator of a lambda or the call
995  // operator template of a generic lambda, update the "instantiation of"
996  // information.
997  auto *NewMD = dyn_cast<CXXMethodDecl>(New);
998  if (NewMD && isLambdaCallOperator(NewMD)) {
999  auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1000  if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1001  NewTD->setInstantiatedFromMemberTemplate(
1002  OldMD->getDescribedFunctionTemplate());
1003  else
1004  NewMD->setInstantiationOfMemberFunction(OldMD,
1006  }
1007 
1008  SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1009 
1010  // We recreated a local declaration, but not by instantiating it. There
1011  // may be pending dependent diagnostics to produce.
1012  if (auto *DC = dyn_cast<DeclContext>(Old))
1013  SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1014  }
1015 
1016  /// Transform the definition of the given declaration by
1017  /// instantiating it.
1018  Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1019 
1020  /// Transform the first qualifier within a scope by instantiating the
1021  /// declaration.
1022  NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1023 
1024  /// Rebuild the exception declaration and register the declaration
1025  /// as an instantiated local.
1026  VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1028  SourceLocation StartLoc,
1029  SourceLocation NameLoc,
1030  IdentifierInfo *Name);
1031 
1032  /// Rebuild the Objective-C exception declaration and register the
1033  /// declaration as an instantiated local.
1034  VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1035  TypeSourceInfo *TSInfo, QualType T);
1036 
1037  /// Check for tag mismatches when instantiating an
1038  /// elaborated type.
1039  QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1040  ElaboratedTypeKeyword Keyword,
1041  NestedNameSpecifierLoc QualifierLoc,
1042  QualType T);
1043 
1044  TemplateName
1045  TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1046  SourceLocation NameLoc,
1047  QualType ObjectType = QualType(),
1048  NamedDecl *FirstQualifierInScope = nullptr,
1049  bool AllowInjectedClassName = false);
1050 
1051  const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1052 
1053  ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1054  ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1055  ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1056 
1057  ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1059  ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1061  ExprResult TransformSubstNonTypeTemplateParmExpr(
1063 
1064  /// Rebuild a DeclRefExpr for a VarDecl reference.
1065  ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1066 
1067  /// Transform a reference to a function or init-capture parameter pack.
1068  ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1069 
1070  /// Transform a FunctionParmPackExpr which was built when we couldn't
1071  /// expand a function parameter pack reference which refers to an expanded
1072  /// pack.
1073  ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1074 
1075  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1076  FunctionProtoTypeLoc TL) {
1077  // Call the base version; it will forward to our overridden version below.
1078  return inherited::TransformFunctionProtoType(TLB, TL);
1079  }
1080 
1081  template<typename Fn>
1082  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1084  CXXRecordDecl *ThisContext,
1085  Qualifiers ThisTypeQuals,
1086  Fn TransformExceptionSpec);
1087 
1088  ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1089  int indexAdjustment,
1090  Optional<unsigned> NumExpansions,
1091  bool ExpectParameterPack);
1092 
1093  /// Transforms a template type parameter type by performing
1094  /// substitution of the corresponding template type argument.
1095  QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1097 
1098  /// Transforms an already-substituted template type parameter pack
1099  /// into either itself (if we aren't substituting into its pack expansion)
1100  /// or the appropriate substituted argument.
1101  QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1103 
1104  ExprResult TransformLambdaExpr(LambdaExpr *E) {
1105  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1107  }
1108 
1109  ExprResult TransformRequiresExpr(RequiresExpr *E) {
1110  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1112  }
1113 
1114  bool TransformRequiresExprRequirements(
1117  bool SatisfactionDetermined = false;
1118  for (concepts::Requirement *Req : Reqs) {
1119  concepts::Requirement *TransReq = nullptr;
1120  if (!SatisfactionDetermined) {
1121  if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1122  TransReq = TransformTypeRequirement(TypeReq);
1123  else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1124  TransReq = TransformExprRequirement(ExprReq);
1125  else
1126  TransReq = TransformNestedRequirement(
1127  cast<concepts::NestedRequirement>(Req));
1128  if (!TransReq)
1129  return true;
1130  if (!TransReq->isDependent() && !TransReq->isSatisfied())
1131  // [expr.prim.req]p6
1132  // [...] The substitution and semantic constraint checking
1133  // proceeds in lexical order and stops when a condition that
1134  // determines the result of the requires-expression is
1135  // encountered. [..]
1136  SatisfactionDetermined = true;
1137  } else
1138  TransReq = Req;
1139  Transformed.push_back(TransReq);
1140  }
1141  return false;
1142  }
1143 
1144  TemplateParameterList *TransformTemplateParameterList(
1145  TemplateParameterList *OrigTPL) {
1146  if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1147 
1148  DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1149  TemplateDeclInstantiator DeclInstantiator(getSema(),
1150  /* DeclContext *Owner */ Owner, TemplateArgs);
1151  return DeclInstantiator.SubstTemplateParams(OrigTPL);
1152  }
1153 
1155  TransformTypeRequirement(concepts::TypeRequirement *Req);
1157  TransformExprRequirement(concepts::ExprRequirement *Req);
1159  TransformNestedRequirement(concepts::NestedRequirement *Req);
1160 
1161  private:
1162  ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1163  SourceLocation loc,
1164  TemplateArgument arg);
1165  };
1166 }
1167 
1168 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1169  if (T.isNull())
1170  return true;
1171 
1173  return false;
1174 
1175  getSema().MarkDeclarationsReferencedInType(Loc, T);
1176  return true;
1177 }
1178 
1179 static TemplateArgument
1181  assert(S.ArgumentPackSubstitutionIndex >= 0);
1182  assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1184  if (Arg.isPackExpansion())
1185  Arg = Arg.getPackExpansionPattern();
1186  return Arg;
1187 }
1188 
1189 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1190  if (!D)
1191  return nullptr;
1192 
1193  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1194  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1195  // If the corresponding template argument is NULL or non-existent, it's
1196  // because we are performing instantiation from explicitly-specified
1197  // template arguments in a function template, but there were some
1198  // arguments left unspecified.
1199  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1200  TTP->getPosition()))
1201  return D;
1202 
1203  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1204 
1205  if (TTP->isParameterPack()) {
1206  assert(Arg.getKind() == TemplateArgument::Pack &&
1207  "Missing argument pack");
1208  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1209  }
1210 
1211  TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1212  assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1213  "Wrong kind of template template argument");
1214  return Template.getAsTemplateDecl();
1215  }
1216 
1217  // Fall through to find the instantiated declaration for this template
1218  // template parameter.
1219  }
1220 
1221  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1222 }
1223 
1224 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1225  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1226  if (!Inst)
1227  return nullptr;
1228 
1229  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1230  return Inst;
1231 }
1232 
1233 NamedDecl *
1234 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1235  SourceLocation Loc) {
1236  // If the first part of the nested-name-specifier was a template type
1237  // parameter, instantiate that type parameter down to a tag type.
1238  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1239  const TemplateTypeParmType *TTP
1240  = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1241 
1242  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1243  // FIXME: This needs testing w/ member access expressions.
1244  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1245 
1246  if (TTP->isParameterPack()) {
1247  assert(Arg.getKind() == TemplateArgument::Pack &&
1248  "Missing argument pack");
1249 
1250  if (getSema().ArgumentPackSubstitutionIndex == -1)
1251  return nullptr;
1252 
1253  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1254  }
1255 
1256  QualType T = Arg.getAsType();
1257  if (T.isNull())
1258  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1259 
1260  if (const TagType *Tag = T->getAs<TagType>())
1261  return Tag->getDecl();
1262 
1263  // The resulting type is not a tag; complain.
1264  getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1265  return nullptr;
1266  }
1267  }
1268 
1269  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1270 }
1271 
1272 VarDecl *
1273 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1275  SourceLocation StartLoc,
1276  SourceLocation NameLoc,
1277  IdentifierInfo *Name) {
1278  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1279  StartLoc, NameLoc, Name);
1280  if (Var)
1281  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1282  return Var;
1283 }
1284 
1285 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1286  TypeSourceInfo *TSInfo,
1287  QualType T) {
1288  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1289  if (Var)
1290  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1291  return Var;
1292 }
1293 
1294 QualType
1295 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1296  ElaboratedTypeKeyword Keyword,
1297  NestedNameSpecifierLoc QualifierLoc,
1298  QualType T) {
1299  if (const TagType *TT = T->getAs<TagType>()) {
1300  TagDecl* TD = TT->getDecl();
1301 
1302  SourceLocation TagLocation = KeywordLoc;
1303 
1304  IdentifierInfo *Id = TD->getIdentifier();
1305 
1306  // TODO: should we even warn on struct/class mismatches for this? Seems
1307  // like it's likely to produce a lot of spurious errors.
1308  if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1310  if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1311  TagLocation, Id)) {
1312  SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1313  << Id
1314  << FixItHint::CreateReplacement(SourceRange(TagLocation),
1315  TD->getKindName());
1316  SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1317  }
1318  }
1319  }
1320 
1322  Keyword,
1323  QualifierLoc,
1324  T);
1325 }
1326 
1327 TemplateName TemplateInstantiator::TransformTemplateName(
1328  CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1329  QualType ObjectType, NamedDecl *FirstQualifierInScope,
1330  bool AllowInjectedClassName) {
1331  if (TemplateTemplateParmDecl *TTP
1332  = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1333  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1334  // If the corresponding template argument is NULL or non-existent, it's
1335  // because we are performing instantiation from explicitly-specified
1336  // template arguments in a function template, but there were some
1337  // arguments left unspecified.
1338  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1339  TTP->getPosition()))
1340  return Name;
1341 
1342  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1343 
1344  if (TTP->isParameterPack()) {
1345  assert(Arg.getKind() == TemplateArgument::Pack &&
1346  "Missing argument pack");
1347 
1348  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1349  // We have the template argument pack to substitute, but we're not
1350  // actually expanding the enclosing pack expansion yet. So, just
1351  // keep the entire argument pack.
1352  return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1353  }
1354 
1355  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1356  }
1357 
1358  TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1359  assert(!Template.isNull() && "Null template template argument");
1360  assert(!Template.getAsQualifiedTemplateName() &&
1361  "template decl to substitute is qualified?");
1362 
1363  Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1364  return Template;
1365  }
1366  }
1367 
1370  if (getSema().ArgumentPackSubstitutionIndex == -1)
1371  return Name;
1372 
1373  TemplateArgument Arg = SubstPack->getArgumentPack();
1374  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1375  return Arg.getAsTemplate().getNameToSubstitute();
1376  }
1377 
1378  return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1379  FirstQualifierInScope,
1380  AllowInjectedClassName);
1381 }
1382 
1383 ExprResult
1384 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1385  if (!E->isTypeDependent())
1386  return E;
1387 
1388  return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1389 }
1390 
1391 ExprResult
1392 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1393  NonTypeTemplateParmDecl *NTTP) {
1394  // If the corresponding template argument is NULL or non-existent, it's
1395  // because we are performing instantiation from explicitly-specified
1396  // template arguments in a function template, but there were some
1397  // arguments left unspecified.
1398  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1399  NTTP->getPosition()))
1400  return E;
1401 
1402  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1403 
1404  if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1405  // We're performing a partial substitution, so the substituted argument
1406  // could be dependent. As a result we can't create a SubstNonType*Expr
1407  // node now, since that represents a fully-substituted argument.
1408  // FIXME: We should have some AST representation for this.
1409  if (Arg.getKind() == TemplateArgument::Pack) {
1410  // FIXME: This won't work for alias templates.
1411  assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1412  "unexpected pack arguments in partial substitution");
1413  Arg = Arg.pack_begin()->getPackExpansionPattern();
1414  }
1415  assert(Arg.getKind() == TemplateArgument::Expression &&
1416  "unexpected nontype template argument kind in partial substitution");
1417  return Arg.getAsExpr();
1418  }
1419 
1420  if (NTTP->isParameterPack()) {
1421  assert(Arg.getKind() == TemplateArgument::Pack &&
1422  "Missing argument pack");
1423 
1424  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1425  // We have an argument pack, but we can't select a particular argument
1426  // out of it yet. Therefore, we'll build an expression to hold on to that
1427  // argument pack.
1428  QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1429  E->getLocation(),
1430  NTTP->getDeclName());
1431  if (TargetType.isNull())
1432  return ExprError();
1433 
1434  return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1435  TargetType.getNonLValueExprType(SemaRef.Context),
1436  TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1437  E->getLocation(), Arg);
1438  }
1439 
1440  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1441  }
1442 
1443  return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1444 }
1445 
1446 const LoopHintAttr *
1447 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1448  Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1449 
1450  if (TransformedExpr == LH->getValue())
1451  return LH;
1452 
1453  // Generate error if there is a problem with the value.
1454  if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1455  return LH;
1456 
1457  // Create new LoopHintValueAttr with integral expression in place of the
1458  // non-type template parameter.
1459  return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1460  LH->getState(), TransformedExpr, *LH);
1461 }
1462 
1463 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1465  SourceLocation loc,
1466  TemplateArgument arg) {
1467  ExprResult result;
1468  QualType type;
1469 
1470  // The template argument itself might be an expression, in which
1471  // case we just return that expression.
1472  if (arg.getKind() == TemplateArgument::Expression) {
1473  Expr *argExpr = arg.getAsExpr();
1474  result = argExpr;
1475  type = argExpr->getType();
1476 
1477  } else if (arg.getKind() == TemplateArgument::Declaration ||
1479  ValueDecl *VD;
1480  if (arg.getKind() == TemplateArgument::Declaration) {
1481  VD = arg.getAsDecl();
1482 
1483  // Find the instantiation of the template argument. This is
1484  // required for nested templates.
1485  VD = cast_or_null<ValueDecl>(
1486  getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1487  if (!VD)
1488  return ExprError();
1489  } else {
1490  // Propagate NULL template argument.
1491  VD = nullptr;
1492  }
1493 
1494  // Derive the type we want the substituted decl to have. This had
1495  // better be non-dependent, or these checks will have serious problems.
1496  if (parm->isExpandedParameterPack()) {
1497  type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1498  } else if (parm->isParameterPack() &&
1499  isa<PackExpansionType>(parm->getType())) {
1500  type = SemaRef.SubstType(
1501  cast<PackExpansionType>(parm->getType())->getPattern(),
1502  TemplateArgs, loc, parm->getDeclName());
1503  } else {
1504  type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1505  TemplateArgs, loc, parm->getDeclName());
1506  }
1507  assert(!type.isNull() && "type substitution failed for param type");
1508  assert(!type->isDependentType() && "param type still dependent");
1509  result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1510 
1511  if (!result.isInvalid()) type = result.get()->getType();
1512  } else {
1513  result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1514 
1515  // Note that this type can be different from the type of 'result',
1516  // e.g. if it's an enum type.
1517  type = arg.getIntegralType();
1518  }
1519  if (result.isInvalid()) return ExprError();
1520 
1521  Expr *resultExpr = result.get();
1522  return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1523  type, resultExpr->getValueKind(), loc, parm, resultExpr);
1524 }
1525 
1526 ExprResult
1527 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1529  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1530  // We aren't expanding the parameter pack, so just return ourselves.
1531  return E;
1532  }
1533 
1534  TemplateArgument Arg = E->getArgumentPack();
1535  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1536  return transformNonTypeTemplateParmRef(E->getParameterPack(),
1538  Arg);
1539 }
1540 
1541 ExprResult
1542 TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1544  ExprResult SubstReplacement = TransformExpr(E->getReplacement());
1545  if (SubstReplacement.isInvalid())
1546  return true;
1547  QualType SubstType = TransformType(E->getType());
1548  if (SubstType.isNull())
1549  return true;
1550  // The type may have been previously dependent and not now, which means we
1551  // might have to implicit cast the argument to the new type, for example:
1552  // template<auto T, decltype(T) U>
1553  // concept C = sizeof(U) == 4;
1554  // void foo() requires C<2, 'a'> { }
1555  // When normalizing foo(), we first form the normalized constraints of C:
1556  // AtomicExpr(sizeof(U) == 4,
1557  // U=SubstNonTypeTemplateParmExpr(Param=U,
1558  // Expr=DeclRef(U),
1559  // Type=decltype(T)))
1560  // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1561  // produce:
1562  // AtomicExpr(sizeof(U) == 4,
1563  // U=SubstNonTypeTemplateParmExpr(Param=U,
1564  // Expr=ImpCast(
1565  // decltype(2),
1566  // SubstNTTPE(Param=U, Expr='a',
1567  // Type=char)),
1568  // Type=decltype(2)))
1569  // The call to CheckTemplateArgument here produces the ImpCast.
1570  TemplateArgument Converted;
1571  if (SemaRef.CheckTemplateArgument(E->getParameter(), SubstType,
1572  SubstReplacement.get(),
1573  Converted).isInvalid())
1574  return true;
1575  return transformNonTypeTemplateParmRef(E->getParameter(),
1576  E->getExprLoc(), Converted);
1577 }
1578 
1579 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1580  SourceLocation Loc) {
1581  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1582  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1583 }
1584 
1585 ExprResult
1586 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1587  if (getSema().ArgumentPackSubstitutionIndex != -1) {
1588  // We can expand this parameter pack now.
1590  VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1591  if (!VD)
1592  return ExprError();
1593  return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1594  }
1595 
1596  QualType T = TransformType(E->getType());
1597  if (T.isNull())
1598  return ExprError();
1599 
1600  // Transform each of the parameter expansions into the corresponding
1601  // parameters in the instantiation of the function decl.
1603  Vars.reserve(E->getNumExpansions());
1604  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1605  I != End; ++I) {
1606  VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1607  if (!D)
1608  return ExprError();
1609  Vars.push_back(D);
1610  }
1611 
1612  auto *PackExpr =
1614  E->getParameterPackLocation(), Vars);
1615  getSema().MarkFunctionParmPackReferenced(PackExpr);
1616  return PackExpr;
1617 }
1618 
1619 ExprResult
1620 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1621  VarDecl *PD) {
1622  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1623  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1624  = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1625  assert(Found && "no instantiation for parameter pack");
1626 
1627  Decl *TransformedDecl;
1628  if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1629  // If this is a reference to a function parameter pack which we can
1630  // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1631  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1632  QualType T = TransformType(E->getType());
1633  if (T.isNull())
1634  return ExprError();
1635  auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1636  E->getExprLoc(), *Pack);
1637  getSema().MarkFunctionParmPackReferenced(PackExpr);
1638  return PackExpr;
1639  }
1640 
1641  TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1642  } else {
1643  TransformedDecl = Found->get<Decl*>();
1644  }
1645 
1646  // We have either an unexpanded pack or a specific expansion.
1647  return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1648 }
1649 
1650 ExprResult
1651 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1652  NamedDecl *D = E->getDecl();
1653 
1654  // Handle references to non-type template parameters and non-type template
1655  // parameter packs.
1656  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1657  if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1658  return TransformTemplateParmRefExpr(E, NTTP);
1659 
1660  // We have a non-type template parameter that isn't fully substituted;
1661  // FindInstantiatedDecl will find it in the local instantiation scope.
1662  }
1663 
1664  // Handle references to function parameter packs.
1665  if (VarDecl *PD = dyn_cast<VarDecl>(D))
1666  if (PD->isParameterPack())
1667  return TransformFunctionParmPackRefExpr(E, PD);
1668 
1670 }
1671 
1672 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1673  CXXDefaultArgExpr *E) {
1674  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1675  getDescribedFunctionTemplate() &&
1676  "Default arg expressions are never formed in dependent cases.");
1677  return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1678  cast<FunctionDecl>(E->getParam()->getDeclContext()),
1679  E->getParam());
1680 }
1681 
1682 template<typename Fn>
1683 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1685  CXXRecordDecl *ThisContext,
1686  Qualifiers ThisTypeQuals,
1687  Fn TransformExceptionSpec) {
1688  // We need a local instantiation scope for this function prototype.
1689  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1690  return inherited::TransformFunctionProtoType(
1691  TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1692 }
1693 
1694 ParmVarDecl *
1695 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1696  int indexAdjustment,
1697  Optional<unsigned> NumExpansions,
1698  bool ExpectParameterPack) {
1699  auto NewParm =
1700  SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1701  NumExpansions, ExpectParameterPack);
1702  if (NewParm && SemaRef.getLangOpts().OpenCL)
1703  SemaRef.deduceOpenCLAddressSpace(NewParm);
1704  return NewParm;
1705 }
1706 
1707 QualType
1708 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1710  const TemplateTypeParmType *T = TL.getTypePtr();
1711  if (T->getDepth() < TemplateArgs.getNumLevels()) {
1712  // Replace the template type parameter with its corresponding
1713  // template argument.
1714 
1715  // If the corresponding template argument is NULL or doesn't exist, it's
1716  // because we are performing instantiation from explicitly-specified
1717  // template arguments in a function template class, but there were some
1718  // arguments left unspecified.
1719  if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1721  = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1722  NewTL.setNameLoc(TL.getNameLoc());
1723  return TL.getType();
1724  }
1725 
1726  TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1727 
1728  if (T->isParameterPack()) {
1729  assert(Arg.getKind() == TemplateArgument::Pack &&
1730  "Missing argument pack");
1731 
1732  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1733  // We have the template argument pack, but we're not expanding the
1734  // enclosing pack expansion yet. Just save the template argument
1735  // pack for later substitution.
1737  = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1740  NewTL.setNameLoc(TL.getNameLoc());
1741  return Result;
1742  }
1743 
1744  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1745  }
1746 
1747  assert(Arg.getKind() == TemplateArgument::Type &&
1748  "Template argument kind mismatch");
1749 
1750  QualType Replacement = Arg.getAsType();
1751 
1752  // TODO: only do this uniquing once, at the start of instantiation.
1754  = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1757  NewTL.setNameLoc(TL.getNameLoc());
1758  return Result;
1759  }
1760 
1761  // The template type parameter comes from an inner template (e.g.,
1762  // the template parameter list of a member template inside the
1763  // template we are instantiating). Create a new template type
1764  // parameter with the template "level" reduced by one.
1765  TemplateTypeParmDecl *NewTTPDecl = nullptr;
1766  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1767  NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1768  TransformDecl(TL.getNameLoc(), OldTTPDecl));
1769 
1770  QualType Result = getSema().Context.getTemplateTypeParmType(
1771  T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1772  T->isParameterPack(), NewTTPDecl);
1774  NewTL.setNameLoc(TL.getNameLoc());
1775  return Result;
1776 }
1777 
1778 QualType
1779 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1780  TypeLocBuilder &TLB,
1782  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1783  // We aren't expanding the parameter pack, so just return ourselves.
1786  NewTL.setNameLoc(TL.getNameLoc());
1787  return TL.getType();
1788  }
1789 
1791  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1792  QualType Result = Arg.getAsType();
1793 
1794  Result = getSema().Context.getSubstTemplateTypeParmType(
1796  Result);
1799  NewTL.setNameLoc(TL.getNameLoc());
1800  return Result;
1801 }
1802 
1803 template<typename EntityPrinter>
1805 createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1806  SmallString<128> Message;
1807  SourceLocation ErrorLoc;
1808  if (Info.hasSFINAEDiagnostic()) {
1811  Info.takeSFINAEDiagnostic(PDA);
1812  PDA.second.EmitToString(S.getDiagnostics(), Message);
1813  ErrorLoc = PDA.first;
1814  } else {
1815  ErrorLoc = Info.getLocation();
1816  }
1817  char *MessageBuf = new (S.Context) char[Message.size()];
1818  std::copy(Message.begin(), Message.end(), MessageBuf);
1819  SmallString<128> Entity;
1820  llvm::raw_svector_ostream OS(Entity);
1821  Printer(OS);
1822  char *EntityBuf = new (S.Context) char[Entity.size()];
1823  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1825  StringRef(EntityBuf, Entity.size()), ErrorLoc,
1826  StringRef(MessageBuf, Message.size())};
1827 }
1828 
1830 TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
1831  if (!Req->isDependent() && !AlwaysRebuild())
1832  return Req;
1833  if (Req->isSubstitutionFailure()) {
1834  if (AlwaysRebuild())
1835  return RebuildTypeRequirement(
1836  Req->getSubstitutionDiagnostic());
1837  return Req;
1838  }
1839 
1840  Sema::SFINAETrap Trap(SemaRef);
1842  Sema::InstantiatingTemplate TypeInst(SemaRef,
1843  Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
1844  Req->getType()->getTypeLoc().getSourceRange());
1845  if (TypeInst.isInvalid())
1846  return nullptr;
1847  TypeSourceInfo *TransType = TransformType(Req->getType());
1848  if (!TransType || Trap.hasErrorOccurred())
1849  return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
1850  [&] (llvm::raw_ostream& OS) {
1851  Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
1852  }));
1853  return RebuildTypeRequirement(TransType);
1854 }
1855 
1857 TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
1858  if (!Req->isDependent() && !AlwaysRebuild())
1859  return Req;
1860 
1861  Sema::SFINAETrap Trap(SemaRef);
1862  TemplateDeductionInfo Info(Req->getExpr()->getBeginLoc());
1863 
1864  llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
1865  TransExpr;
1866  if (Req->isExprSubstitutionFailure())
1867  TransExpr = Req->getExprSubstitutionDiagnostic();
1868  else {
1869  Sema::InstantiatingTemplate ExprInst(SemaRef, Req->getExpr()->getBeginLoc(),
1870  Req, Info,
1871  Req->getExpr()->getSourceRange());
1872  if (ExprInst.isInvalid())
1873  return nullptr;
1874  ExprResult TransExprRes = TransformExpr(Req->getExpr());
1875  if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
1876  TransExpr = createSubstDiag(SemaRef, Info,
1877  [&] (llvm::raw_ostream& OS) {
1878  Req->getExpr()->printPretty(OS, nullptr,
1879  SemaRef.getPrintingPolicy());
1880  });
1881  else
1882  TransExpr = TransExprRes.get();
1883  }
1884 
1886  const auto &RetReq = Req->getReturnTypeRequirement();
1887  if (RetReq.isEmpty())
1888  TransRetReq.emplace();
1889  else if (RetReq.isSubstitutionFailure())
1890  TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
1891  else if (RetReq.isTypeConstraint()) {
1892  TemplateParameterList *OrigTPL =
1893  RetReq.getTypeConstraintTemplateParameterList();
1894  Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
1895  Req, Info, OrigTPL->getSourceRange());
1896  if (TPLInst.isInvalid())
1897  return nullptr;
1898  TemplateParameterList *TPL =
1899  TransformTemplateParameterList(OrigTPL);
1900  if (!TPL)
1901  TransRetReq.emplace(createSubstDiag(SemaRef, Info,
1902  [&] (llvm::raw_ostream& OS) {
1903  RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
1904  ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
1905  }));
1906  else {
1907  TPLInst.Clear();
1908  TransRetReq.emplace(TPL);
1909  }
1910  }
1911  assert(TransRetReq.hasValue() &&
1912  "All code paths leading here must set TransRetReq");
1913  if (Expr *E = TransExpr.dyn_cast<Expr *>())
1914  return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
1915  std::move(*TransRetReq));
1916  return RebuildExprRequirement(
1918  Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
1919 }
1920 
1922 TemplateInstantiator::TransformNestedRequirement(
1924  if (!Req->isDependent() && !AlwaysRebuild())
1925  return Req;
1926  if (Req->isSubstitutionFailure()) {
1927  if (AlwaysRebuild())
1928  return RebuildNestedRequirement(
1929  Req->getSubstitutionDiagnostic());
1930  return Req;
1931  }
1932  Sema::InstantiatingTemplate ReqInst(SemaRef,
1933  Req->getConstraintExpr()->getBeginLoc(), Req,
1935  Req->getConstraintExpr()->getSourceRange());
1936 
1937  ExprResult TransConstraint;
1939  {
1942  Sema::SFINAETrap Trap(SemaRef);
1943  Sema::InstantiatingTemplate ConstrInst(SemaRef,
1944  Req->getConstraintExpr()->getBeginLoc(), Req, Info,
1945  Req->getConstraintExpr()->getSourceRange());
1946  if (ConstrInst.isInvalid())
1947  return nullptr;
1948  TransConstraint = TransformExpr(Req->getConstraintExpr());
1949  if (TransConstraint.isInvalid() || Trap.hasErrorOccurred())
1950  return RebuildNestedRequirement(createSubstDiag(SemaRef, Info,
1951  [&] (llvm::raw_ostream& OS) {
1952  Req->getConstraintExpr()->printPretty(OS, nullptr,
1953  SemaRef.getPrintingPolicy());
1954  }));
1955  }
1956  return RebuildNestedRequirement(TransConstraint.get());
1957 }
1958 
1959 
1960 /// Perform substitution on the type T with a given set of template
1961 /// arguments.
1962 ///
1963 /// This routine substitutes the given template arguments into the
1964 /// type T and produces the instantiated type.
1965 ///
1966 /// \param T the type into which the template arguments will be
1967 /// substituted. If this type is not dependent, it will be returned
1968 /// immediately.
1969 ///
1970 /// \param Args the template arguments that will be
1971 /// substituted for the top-level template parameters within T.
1972 ///
1973 /// \param Loc the location in the source code where this substitution
1974 /// is being performed. It will typically be the location of the
1975 /// declarator (if we're instantiating the type of some declaration)
1976 /// or the location of the type in the source code (if, e.g., we're
1977 /// instantiating the type of a cast expression).
1978 ///
1979 /// \param Entity the name of the entity associated with a declaration
1980 /// being instantiated (if any). May be empty to indicate that there
1981 /// is no such entity (if, e.g., this is a type that occurs as part of
1982 /// a cast expression) or that the entity has no name (e.g., an
1983 /// unnamed function parameter).
1984 ///
1985 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1986 /// acceptable as the top level type of the result.
1987 ///
1988 /// \returns If the instantiation succeeds, the instantiated
1989 /// type. Otherwise, produces diagnostics and returns a NULL type.
1991  const MultiLevelTemplateArgumentList &Args,
1992  SourceLocation Loc,
1993  DeclarationName Entity,
1994  bool AllowDeducedTST) {
1995  assert(!CodeSynthesisContexts.empty() &&
1996  "Cannot perform an instantiation without some context on the "
1997  "instantiation stack");
1998 
1999  if (!T->getType()->isInstantiationDependentType() &&
2001  return T;
2002 
2003  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2004  return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2005  : Instantiator.TransformType(T);
2006 }
2007 
2009  const MultiLevelTemplateArgumentList &Args,
2010  SourceLocation Loc,
2011  DeclarationName Entity) {
2012  assert(!CodeSynthesisContexts.empty() &&
2013  "Cannot perform an instantiation without some context on the "
2014  "instantiation stack");
2015 
2016  if (TL.getType().isNull())
2017  return nullptr;
2018 
2019  if (!TL.getType()->isInstantiationDependentType() &&
2020  !TL.getType()->isVariablyModifiedType()) {
2021  // FIXME: Make a copy of the TypeLoc data here, so that we can
2022  // return a new TypeSourceInfo. Inefficient!
2023  TypeLocBuilder TLB;
2024  TLB.pushFullCopy(TL);
2025  return TLB.getTypeSourceInfo(Context, TL.getType());
2026  }
2027 
2028  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2029  TypeLocBuilder TLB;
2030  TLB.reserve(TL.getFullDataSize());
2031  QualType Result = Instantiator.TransformType(TLB, TL);
2032  if (Result.isNull())
2033  return nullptr;
2034 
2035  return TLB.getTypeSourceInfo(Context, Result);
2036 }
2037 
2038 /// Deprecated form of the above.
2040  const MultiLevelTemplateArgumentList &TemplateArgs,
2041  SourceLocation Loc, DeclarationName Entity) {
2042  assert(!CodeSynthesisContexts.empty() &&
2043  "Cannot perform an instantiation without some context on the "
2044  "instantiation stack");
2045 
2046  // If T is not a dependent type or a variably-modified type, there
2047  // is nothing to do.
2049  return T;
2050 
2051  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2052  return Instantiator.TransformType(T);
2053 }
2054 
2056  if (T->getType()->isInstantiationDependentType() ||
2058  return true;
2059 
2060  TypeLoc TL = T->getTypeLoc().IgnoreParens();
2061  if (!TL.getAs<FunctionProtoTypeLoc>())
2062  return false;
2063 
2065  for (ParmVarDecl *P : FP.getParams()) {
2066  // This must be synthesized from a typedef.
2067  if (!P) continue;
2068 
2069  // If there are any parameters, a new TypeSourceInfo that refers to the
2070  // instantiated parameters must be built.
2071  return true;
2072  }
2073 
2074  return false;
2075 }
2076 
2077 /// A form of SubstType intended specifically for instantiating the
2078 /// type of a FunctionDecl. Its purpose is solely to force the
2079 /// instantiation of default-argument expressions and to avoid
2080 /// instantiating an exception-specification.
2082  const MultiLevelTemplateArgumentList &Args,
2083  SourceLocation Loc,
2084  DeclarationName Entity,
2085  CXXRecordDecl *ThisContext,
2086  Qualifiers ThisTypeQuals) {
2087  assert(!CodeSynthesisContexts.empty() &&
2088  "Cannot perform an instantiation without some context on the "
2089  "instantiation stack");
2090 
2092  return T;
2093 
2094  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2095 
2096  TypeLocBuilder TLB;
2097 
2098  TypeLoc TL = T->getTypeLoc();
2099  TLB.reserve(TL.getFullDataSize());
2100 
2101  QualType Result;
2102 
2103  if (FunctionProtoTypeLoc Proto =
2105  // Instantiate the type, other than its exception specification. The
2106  // exception specification is instantiated in InitFunctionInstantiation
2107  // once we've built the FunctionDecl.
2108  // FIXME: Set the exception specification to EST_Uninstantiated here,
2109  // instead of rebuilding the function type again later.
2110  Result = Instantiator.TransformFunctionProtoType(
2111  TLB, Proto, ThisContext, ThisTypeQuals,
2113  bool &Changed) { return false; });
2114  } else {
2115  Result = Instantiator.TransformType(TLB, TL);
2116  }
2117  if (Result.isNull())
2118  return nullptr;
2119 
2120  return TLB.getTypeSourceInfo(Context, Result);
2121 }
2122 
2125  SmallVectorImpl<QualType> &ExceptionStorage,
2126  const MultiLevelTemplateArgumentList &Args) {
2127  assert(ESI.Type != EST_Uninstantiated);
2128 
2129  bool Changed = false;
2130  TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2131  return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2132  Changed);
2133 }
2134 
2136  const MultiLevelTemplateArgumentList &Args) {
2138  Proto->getExtProtoInfo().ExceptionSpec;
2139 
2140  SmallVector<QualType, 4> ExceptionStorage;
2142  ESI, ExceptionStorage, Args))
2143  // On error, recover by dropping the exception specification.
2144  ESI.Type = EST_None;
2145 
2146  UpdateExceptionSpec(New, ESI);
2147 }
2148 
2149 namespace {
2150 
2151  struct GetContainedInventedTypeParmVisitor :
2152  public TypeVisitor<GetContainedInventedTypeParmVisitor,
2153  TemplateTypeParmDecl *> {
2154  using TypeVisitor<GetContainedInventedTypeParmVisitor,
2155  TemplateTypeParmDecl *>::Visit;
2156 
2157  TemplateTypeParmDecl *Visit(QualType T) {
2158  if (T.isNull())
2159  return nullptr;
2160  return Visit(T.getTypePtr());
2161  }
2162  // The deduced type itself.
2163  TemplateTypeParmDecl *VisitTemplateTypeParmType(
2164  const TemplateTypeParmType *T) {
2165  if (!T->getDecl()->isImplicit())
2166  return nullptr;
2167  return T->getDecl();
2168  }
2169 
2170  // Only these types can contain 'auto' types, and subsequently be replaced
2171  // by references to invented parameters.
2172 
2173  TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2174  return Visit(T->getNamedType());
2175  }
2176 
2177  TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2178  return Visit(T->getPointeeType());
2179  }
2180 
2181  TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2182  return Visit(T->getPointeeType());
2183  }
2184 
2185  TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2186  return Visit(T->getPointeeTypeAsWritten());
2187  }
2188 
2189  TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2190  return Visit(T->getPointeeType());
2191  }
2192 
2193  TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2194  return Visit(T->getElementType());
2195  }
2196 
2197  TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2198  const DependentSizedExtVectorType *T) {
2199  return Visit(T->getElementType());
2200  }
2201 
2202  TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2203  return Visit(T->getElementType());
2204  }
2205 
2206  TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2207  return VisitFunctionType(T);
2208  }
2209 
2210  TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2211  return Visit(T->getReturnType());
2212  }
2213 
2214  TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2215  return Visit(T->getInnerType());
2216  }
2217 
2218  TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2219  return Visit(T->getModifiedType());
2220  }
2221 
2222  TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2223  return Visit(T->getUnderlyingType());
2224  }
2225 
2226  TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2227  return Visit(T->getOriginalType());
2228  }
2229 
2230  TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2231  return Visit(T->getPattern());
2232  }
2233  };
2234 
2235 } // namespace
2236 
2238  const MultiLevelTemplateArgumentList &TemplateArgs,
2239  int indexAdjustment,
2240  Optional<unsigned> NumExpansions,
2241  bool ExpectParameterPack) {
2242  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2243  TypeSourceInfo *NewDI = nullptr;
2244 
2245  TypeLoc OldTL = OldDI->getTypeLoc();
2246  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2247 
2248  // We have a function parameter pack. Substitute into the pattern of the
2249  // expansion.
2250  NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2251  OldParm->getLocation(), OldParm->getDeclName());
2252  if (!NewDI)
2253  return nullptr;
2254 
2255  if (NewDI->getType()->containsUnexpandedParameterPack()) {
2256  // We still have unexpanded parameter packs, which means that
2257  // our function parameter is still a function parameter pack.
2258  // Therefore, make its type a pack expansion type.
2259  NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2260  NumExpansions);
2261  } else if (ExpectParameterPack) {
2262  // We expected to get a parameter pack but didn't (because the type
2263  // itself is not a pack expansion type), so complain. This can occur when
2264  // the substitution goes through an alias template that "loses" the
2265  // pack expansion.
2266  Diag(OldParm->getLocation(),
2267  diag::err_function_parameter_pack_without_parameter_packs)
2268  << NewDI->getType();
2269  return nullptr;
2270  }
2271  } else {
2272  NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2273  OldParm->getDeclName());
2274  }
2275 
2276  if (!NewDI)
2277  return nullptr;
2278 
2279  if (NewDI->getType()->isVoidType()) {
2280  Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2281  return nullptr;
2282  }
2283 
2284  // In abbreviated templates, TemplateTypeParmDecls with possible
2285  // TypeConstraints are created when the parameter list is originally parsed.
2286  // The TypeConstraints can therefore reference other functions parameters in
2287  // the abbreviated function template, which is why we must instantiate them
2288  // here, when the instantiated versions of those referenced parameters are in
2289  // scope.
2290  if (TemplateTypeParmDecl *TTP =
2291  GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2292  if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2293  auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2294  FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2295  // We will first get here when instantiating the abbreviated function
2296  // template's described function, but we might also get here later.
2297  // Make sure we do not instantiate the TypeConstraint more than once.
2298  if (Inst && !Inst->getTypeConstraint()) {
2299  // TODO: Concepts: do not instantiate the constraint (delayed constraint
2300  // substitution)
2301  const ASTTemplateArgumentListInfo *TemplArgInfo
2302  = TC->getTemplateArgsAsWritten();
2303  TemplateArgumentListInfo InstArgs;
2304 
2305  if (TemplArgInfo) {
2306  InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2307  InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2308  if (Subst(TemplArgInfo->getTemplateArgs(),
2309  TemplArgInfo->NumTemplateArgs, InstArgs, TemplateArgs))
2310  return nullptr;
2311  }
2313  TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2314  TC->getNamedConcept(), &InstArgs, Inst,
2315  TTP->isParameterPack()
2316  ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2317  ->getEllipsisLoc()
2318  : SourceLocation()))
2319  return nullptr;
2320  }
2321  }
2322  }
2323 
2325  OldParm->getInnerLocStart(),
2326  OldParm->getLocation(),
2327  OldParm->getIdentifier(),
2328  NewDI->getType(), NewDI,
2329  OldParm->getStorageClass());
2330  if (!NewParm)
2331  return nullptr;
2332 
2333  // Mark the (new) default argument as uninstantiated (if any).
2334  if (OldParm->hasUninstantiatedDefaultArg()) {
2335  Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2336  NewParm->setUninstantiatedDefaultArg(Arg);
2337  } else if (OldParm->hasUnparsedDefaultArg()) {
2338  NewParm->setUnparsedDefaultArg();
2339  UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2340  } else if (Expr *Arg = OldParm->getDefaultArg()) {
2341  FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
2342  if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
2343  // Instantiate default arguments for methods of local classes (DR1484)
2344  // and non-defining declarations.
2345  Sema::ContextRAII SavedContext(*this, OwningFunc);
2346  LocalInstantiationScope Local(*this, true);
2347  ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
2348  if (NewArg.isUsable()) {
2349  // It would be nice if we still had this.
2350  SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
2351  SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
2352  }
2353  } else {
2354  // FIXME: if we non-lazily instantiated non-dependent default args for
2355  // non-dependent parameter types we could remove a bunch of duplicate
2356  // conversion warnings for such arguments.
2357  NewParm->setUninstantiatedDefaultArg(Arg);
2358  }
2359  }
2360 
2362 
2363  if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
2364  // Add the new parameter to the instantiated parameter pack.
2366  } else {
2367  // Introduce an Old -> New mapping
2368  CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
2369  }
2370 
2371  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2372  // can be anything, is this right ?
2373  NewParm->setDeclContext(CurContext);
2374 
2375  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2376  OldParm->getFunctionScopeIndex() + indexAdjustment);
2377 
2378  InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2379 
2380  return NewParm;
2381 }
2382 
2383 /// Substitute the given template arguments into the given set of
2384 /// parameters, producing the set of parameter types that would be generated
2385 /// from such a substitution.
2388  const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2389  const MultiLevelTemplateArgumentList &TemplateArgs,
2390  SmallVectorImpl<QualType> &ParamTypes,
2391  SmallVectorImpl<ParmVarDecl *> *OutParams,
2392  ExtParameterInfoBuilder &ParamInfos) {
2393  assert(!CodeSynthesisContexts.empty() &&
2394  "Cannot perform an instantiation without some context on the "
2395  "instantiation stack");
2396 
2397  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2398  DeclarationName());
2399  return Instantiator.TransformFunctionTypeParams(
2400  Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2401 }
2402 
2403 /// Perform substitution on the base class specifiers of the
2404 /// given class template specialization.
2405 ///
2406 /// Produces a diagnostic and returns true on error, returns false and
2407 /// attaches the instantiated base classes to the class template
2408 /// specialization if successful.
2409 bool
2411  CXXRecordDecl *Pattern,
2412  const MultiLevelTemplateArgumentList &TemplateArgs) {
2413  bool Invalid = false;
2414  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
2415  for (const auto &Base : Pattern->bases()) {
2416  if (!Base.getType()->isDependentType()) {
2417  if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2418  if (RD->isInvalidDecl())
2419  Instantiation->setInvalidDecl();
2420  }
2421  InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2422  continue;
2423  }
2424 
2425  SourceLocation EllipsisLoc;
2426  TypeSourceInfo *BaseTypeLoc;
2427  if (Base.isPackExpansion()) {
2428  // This is a pack expansion. See whether we should expand it now, or
2429  // wait until later.
2431  collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2432  Unexpanded);
2433  bool ShouldExpand = false;
2434  bool RetainExpansion = false;
2435  Optional<unsigned> NumExpansions;
2436  if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2437  Base.getSourceRange(),
2438  Unexpanded,
2439  TemplateArgs, ShouldExpand,
2440  RetainExpansion,
2441  NumExpansions)) {
2442  Invalid = true;
2443  continue;
2444  }
2445 
2446  // If we should expand this pack expansion now, do so.
2447  if (ShouldExpand) {
2448  for (unsigned I = 0; I != *NumExpansions; ++I) {
2449  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2450 
2451  TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2452  TemplateArgs,
2453  Base.getSourceRange().getBegin(),
2454  DeclarationName());
2455  if (!BaseTypeLoc) {
2456  Invalid = true;
2457  continue;
2458  }
2459 
2460  if (CXXBaseSpecifier *InstantiatedBase
2461  = CheckBaseSpecifier(Instantiation,
2462  Base.getSourceRange(),
2463  Base.isVirtual(),
2464  Base.getAccessSpecifierAsWritten(),
2465  BaseTypeLoc,
2466  SourceLocation()))
2467  InstantiatedBases.push_back(InstantiatedBase);
2468  else
2469  Invalid = true;
2470  }
2471 
2472  continue;
2473  }
2474 
2475  // The resulting base specifier will (still) be a pack expansion.
2476  EllipsisLoc = Base.getEllipsisLoc();
2477  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2478  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2479  TemplateArgs,
2480  Base.getSourceRange().getBegin(),
2481  DeclarationName());
2482  } else {
2483  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2484  TemplateArgs,
2485  Base.getSourceRange().getBegin(),
2486  DeclarationName());
2487  }
2488 
2489  if (!BaseTypeLoc) {
2490  Invalid = true;
2491  continue;
2492  }
2493 
2494  if (CXXBaseSpecifier *InstantiatedBase
2495  = CheckBaseSpecifier(Instantiation,
2496  Base.getSourceRange(),
2497  Base.isVirtual(),
2498  Base.getAccessSpecifierAsWritten(),
2499  BaseTypeLoc,
2500  EllipsisLoc))
2501  InstantiatedBases.push_back(InstantiatedBase);
2502  else
2503  Invalid = true;
2504  }
2505 
2506  if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
2507  Invalid = true;
2508 
2509  return Invalid;
2510 }
2511 
2512 // Defined via #include from SemaTemplateInstantiateDecl.cpp
2513 namespace clang {
2514  namespace sema {
2516  const MultiLevelTemplateArgumentList &TemplateArgs);
2518  const Attr *At, ASTContext &C, Sema &S,
2519  const MultiLevelTemplateArgumentList &TemplateArgs);
2520  }
2521 }
2522 
2523 /// Instantiate the definition of a class from a given pattern.
2524 ///
2525 /// \param PointOfInstantiation The point of instantiation within the
2526 /// source code.
2527 ///
2528 /// \param Instantiation is the declaration whose definition is being
2529 /// instantiated. This will be either a class template specialization
2530 /// or a member class of a class template specialization.
2531 ///
2532 /// \param Pattern is the pattern from which the instantiation
2533 /// occurs. This will be either the declaration of a class template or
2534 /// the declaration of a member class of a class template.
2535 ///
2536 /// \param TemplateArgs The template arguments to be substituted into
2537 /// the pattern.
2538 ///
2539 /// \param TSK the kind of implicit or explicit instantiation to perform.
2540 ///
2541 /// \param Complain whether to complain if the class cannot be instantiated due
2542 /// to the lack of a definition.
2543 ///
2544 /// \returns true if an error occurred, false otherwise.
2545 bool
2547  CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2548  const MultiLevelTemplateArgumentList &TemplateArgs,
2550  bool Complain) {
2551  CXXRecordDecl *PatternDef
2552  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2553  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2554  Instantiation->getInstantiatedFromMemberClass(),
2555  Pattern, PatternDef, TSK, Complain))
2556  return true;
2557 
2558  llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2559  std::string Name;
2560  llvm::raw_string_ostream OS(Name);
2561  Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2562  /*Qualified=*/true);
2563  return Name;
2564  });
2565 
2566  Pattern = PatternDef;
2567 
2568  // Record the point of instantiation.
2569  if (MemberSpecializationInfo *MSInfo
2570  = Instantiation->getMemberSpecializationInfo()) {
2571  MSInfo->setTemplateSpecializationKind(TSK);
2572  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2573  } else if (ClassTemplateSpecializationDecl *Spec
2574  = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2575  Spec->setTemplateSpecializationKind(TSK);
2576  Spec->setPointOfInstantiation(PointOfInstantiation);
2577  }
2578 
2579  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2580  if (Inst.isInvalid())
2581  return true;
2582  assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2583  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2584  "instantiating class definition");
2585 
2586  // Enter the scope of this instantiation. We don't use
2587  // PushDeclContext because we don't have a scope.
2588  ContextRAII SavedContext(*this, Instantiation);
2591 
2592  // If this is an instantiation of a local class, merge this local
2593  // instantiation scope with the enclosing scope. Otherwise, every
2594  // instantiation of a class has its own local instantiation scope.
2595  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2596  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2597 
2598  // Some class state isn't processed immediately but delayed till class
2599  // instantiation completes. We may not be ready to handle any delayed state
2600  // already on the stack as it might correspond to a different class, so save
2601  // it now and put it back later.
2602  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2603 
2604  // Pull attributes from the pattern onto the instantiation.
2605  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2606 
2607  // Start the definition of this instantiation.
2608  Instantiation->startDefinition();
2609 
2610  // The instantiation is visible here, even if it was first declared in an
2611  // unimported module.
2612  Instantiation->setVisibleDespiteOwningModule();
2613 
2614  // FIXME: This loses the as-written tag kind for an explicit instantiation.
2615  Instantiation->setTagKind(Pattern->getTagKind());
2616 
2617  // Do substitution on the base class specifiers.
2618  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2619  Instantiation->setInvalidDecl();
2620 
2621  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2622  SmallVector<Decl*, 4> Fields;
2623  // Delay instantiation of late parsed attributes.
2624  LateInstantiatedAttrVec LateAttrs;
2625  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2626 
2627  bool MightHaveConstexprVirtualFunctions = false;
2628  for (auto *Member : Pattern->decls()) {
2629  // Don't instantiate members not belonging in this semantic context.
2630  // e.g. for:
2631  // @code
2632  // template <int i> class A {
2633  // class B *g;
2634  // };
2635  // @endcode
2636  // 'class B' has the template as lexical context but semantically it is
2637  // introduced in namespace scope.
2638  if (Member->getDeclContext() != Pattern)
2639  continue;
2640 
2641  // BlockDecls can appear in a default-member-initializer. They must be the
2642  // child of a BlockExpr, so we only know how to instantiate them from there.
2643  if (isa<BlockDecl>(Member))
2644  continue;
2645 
2646  if (Member->isInvalidDecl()) {
2647  Instantiation->setInvalidDecl();
2648  continue;
2649  }
2650 
2651  Decl *NewMember = Instantiator.Visit(Member);
2652  if (NewMember) {
2653  if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2654  Fields.push_back(Field);
2655  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2656  // C++11 [temp.inst]p1: The implicit instantiation of a class template
2657  // specialization causes the implicit instantiation of the definitions
2658  // of unscoped member enumerations.
2659  // Record a point of instantiation for this implicit instantiation.
2660  if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2661  Enum->isCompleteDefinition()) {
2662  MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2663  assert(MSInfo && "no spec info for member enum specialization");
2665  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2666  }
2667  } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2668  if (SA->isFailed()) {
2669  // A static_assert failed. Bail out; instantiating this
2670  // class is probably not meaningful.
2671  Instantiation->setInvalidDecl();
2672  break;
2673  }
2674  } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2675  if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2676  (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2677  MightHaveConstexprVirtualFunctions = true;
2678  }
2679 
2680  if (NewMember->isInvalidDecl())
2681  Instantiation->setInvalidDecl();
2682  } else {
2683  // FIXME: Eventually, a NULL return will mean that one of the
2684  // instantiations was a semantic disaster, and we'll want to mark the
2685  // declaration invalid.
2686  // For now, we expect to skip some members that we can't yet handle.
2687  }
2688  }
2689 
2690  // Finish checking fields.
2691  ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2693  CheckCompletedCXXClass(nullptr, Instantiation);
2694 
2695  // Default arguments are parsed, if not instantiated. We can go instantiate
2696  // default arg exprs for default constructors if necessary now. Unless we're
2697  // parsing a class, in which case wait until that's finished.
2698  if (ParsingClassDepth == 0)
2700 
2701  // Instantiate late parsed attributes, and attach them to their decls.
2702  // See Sema::InstantiateAttrs
2703  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2704  E = LateAttrs.end(); I != E; ++I) {
2705  assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2706  CurrentInstantiationScope = I->Scope;
2707 
2708  // Allow 'this' within late-parsed attributes.
2709  NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2710  CXXRecordDecl *ThisContext =
2711  dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2712  CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2713  ND && ND->isCXXInstanceMember());
2714 
2715  Attr *NewAttr =
2716  instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2717  I->NewDecl->addAttr(NewAttr);
2719  Instantiator.getStartingScope());
2720  }
2721  Instantiator.disableLateAttributeInstantiation();
2722  LateAttrs.clear();
2723 
2724  ActOnFinishDelayedMemberInitializers(Instantiation);
2725 
2726  // FIXME: We should do something similar for explicit instantiations so they
2727  // end up in the right module.
2728  if (TSK == TSK_ImplicitInstantiation) {
2729  Instantiation->setLocation(Pattern->getLocation());
2730  Instantiation->setLocStart(Pattern->getInnerLocStart());
2731  Instantiation->setBraceRange(Pattern->getBraceRange());
2732  }
2733 
2734  if (!Instantiation->isInvalidDecl()) {
2735  // Perform any dependent diagnostics from the pattern.
2736  PerformDependentDiagnostics(Pattern, TemplateArgs);
2737 
2738  // Instantiate any out-of-line class template partial
2739  // specializations now.
2741  P = Instantiator.delayed_partial_spec_begin(),
2742  PEnd = Instantiator.delayed_partial_spec_end();
2743  P != PEnd; ++P) {
2745  P->first, P->second)) {
2746  Instantiation->setInvalidDecl();
2747  break;
2748  }
2749  }
2750 
2751  // Instantiate any out-of-line variable template partial
2752  // specializations now.
2754  P = Instantiator.delayed_var_partial_spec_begin(),
2755  PEnd = Instantiator.delayed_var_partial_spec_end();
2756  P != PEnd; ++P) {
2758  P->first, P->second)) {
2759  Instantiation->setInvalidDecl();
2760  break;
2761  }
2762  }
2763  }
2764 
2765  // Exit the scope of this instantiation.
2766  SavedContext.pop();
2767 
2768  if (!Instantiation->isInvalidDecl()) {
2769  Consumer.HandleTagDeclDefinition(Instantiation);
2770 
2771  // Always emit the vtable for an explicit instantiation definition
2772  // of a polymorphic class template specialization. Otherwise, eagerly
2773  // instantiate only constexpr virtual functions in preparation for their use
2774  // in constant evaluation.
2776  MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2777  else if (MightHaveConstexprVirtualFunctions)
2778  MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2779  /*ConstexprOnly*/ true);
2780  }
2781 
2782  return Instantiation->isInvalidDecl();
2783 }
2784 
2785 /// Instantiate the definition of an enum from a given pattern.
2786 ///
2787 /// \param PointOfInstantiation The point of instantiation within the
2788 /// source code.
2789 /// \param Instantiation is the declaration whose definition is being
2790 /// instantiated. This will be a member enumeration of a class
2791 /// temploid specialization, or a local enumeration within a
2792 /// function temploid specialization.
2793 /// \param Pattern The templated declaration from which the instantiation
2794 /// occurs.
2795 /// \param TemplateArgs The template arguments to be substituted into
2796 /// the pattern.
2797 /// \param TSK The kind of implicit or explicit instantiation to perform.
2798 ///
2799 /// \return \c true if an error occurred, \c false otherwise.
2800 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2801  EnumDecl *Instantiation, EnumDecl *Pattern,
2802  const MultiLevelTemplateArgumentList &TemplateArgs,
2804  EnumDecl *PatternDef = Pattern->getDefinition();
2805  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2806  Instantiation->getInstantiatedFromMemberEnum(),
2807  Pattern, PatternDef, TSK,/*Complain*/true))
2808  return true;
2809  Pattern = PatternDef;
2810 
2811  // Record the point of instantiation.
2812  if (MemberSpecializationInfo *MSInfo
2813  = Instantiation->getMemberSpecializationInfo()) {
2814  MSInfo->setTemplateSpecializationKind(TSK);
2815  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2816  }
2817 
2818  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2819  if (Inst.isInvalid())
2820  return true;
2821  if (Inst.isAlreadyInstantiating())
2822  return false;
2823  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2824  "instantiating enum definition");
2825 
2826  // The instantiation is visible here, even if it was first declared in an
2827  // unimported module.
2828  Instantiation->setVisibleDespiteOwningModule();
2829 
2830  // Enter the scope of this instantiation. We don't use
2831  // PushDeclContext because we don't have a scope.
2832  ContextRAII SavedContext(*this, Instantiation);
2835 
2836  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2837 
2838  // Pull attributes from the pattern onto the instantiation.
2839  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2840 
2841  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2842  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2843 
2844  // Exit the scope of this instantiation.
2845  SavedContext.pop();
2846 
2847  return Instantiation->isInvalidDecl();
2848 }
2849 
2850 
2851 /// Instantiate the definition of a field from the given pattern.
2852 ///
2853 /// \param PointOfInstantiation The point of instantiation within the
2854 /// source code.
2855 /// \param Instantiation is the declaration whose definition is being
2856 /// instantiated. This will be a class of a class temploid
2857 /// specialization, or a local enumeration within a function temploid
2858 /// specialization.
2859 /// \param Pattern The templated declaration from which the instantiation
2860 /// occurs.
2861 /// \param TemplateArgs The template arguments to be substituted into
2862 /// the pattern.
2863 ///
2864 /// \return \c true if an error occurred, \c false otherwise.
2866  SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2867  FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2868  // If there is no initializer, we don't need to do anything.
2869  if (!Pattern->hasInClassInitializer())
2870  return false;
2871 
2872  assert(Instantiation->getInClassInitStyle() ==
2873  Pattern->getInClassInitStyle() &&
2874  "pattern and instantiation disagree about init style");
2875 
2876  // Error out if we haven't parsed the initializer of the pattern yet because
2877  // we are waiting for the closing brace of the outer class.
2878  Expr *OldInit = Pattern->getInClassInitializer();
2879  if (!OldInit) {
2880  RecordDecl *PatternRD = Pattern->getParent();
2881  RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2882  Diag(PointOfInstantiation,
2883  diag::err_in_class_initializer_not_yet_parsed)
2884  << OutermostClass << Pattern;
2885  Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
2886  Instantiation->setInvalidDecl();
2887  return true;
2888  }
2889 
2890  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2891  if (Inst.isInvalid())
2892  return true;
2893  if (Inst.isAlreadyInstantiating()) {
2894  // Error out if we hit an instantiation cycle for this initializer.
2895  Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2896  << Instantiation;
2897  return true;
2898  }
2899  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2900  "instantiating default member init");
2901 
2902  // Enter the scope of this instantiation. We don't use PushDeclContext because
2903  // we don't have a scope.
2904  ContextRAII SavedContext(*this, Instantiation->getParent());
2907 
2908  LocalInstantiationScope Scope(*this, true);
2909 
2910  // Instantiate the initializer.
2912  CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
2913 
2914  ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2915  /*CXXDirectInit=*/false);
2916  Expr *Init = NewInit.get();
2917  assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2919  Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
2920 
2921  if (auto *L = getASTMutationListener())
2922  L->DefaultMemberInitializerInstantiated(Instantiation);
2923 
2924  // Return true if the in-class initializer is still missing.
2925  return !Instantiation->getInClassInitializer();
2926 }
2927 
2928 namespace {
2929  /// A partial specialization whose template arguments have matched
2930  /// a given template-id.
2931  struct PartialSpecMatchResult {
2933  TemplateArgumentList *Args;
2934  };
2935 }
2936 
2938  SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2939  if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2941  return true;
2942 
2944  ClassTemplateSpec->getSpecializedTemplate()
2945  ->getPartialSpecializations(PartialSpecs);
2946  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2947  TemplateDeductionInfo Info(Loc);
2948  if (!DeduceTemplateArguments(PartialSpecs[I],
2949  ClassTemplateSpec->getTemplateArgs(), Info))
2950  return true;
2951  }
2952 
2953  return false;
2954 }
2955 
2956 /// Get the instantiation pattern to use to instantiate the definition of a
2957 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2958 /// template or of a partial specialization).
2959 static CXXRecordDecl *
2961  Sema &S, SourceLocation PointOfInstantiation,
2962  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2963  TemplateSpecializationKind TSK, bool Complain) {
2964  Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2965  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2966  return nullptr;
2967 
2968  llvm::PointerUnion<ClassTemplateDecl *,
2970  Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2971  if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2972  // Find best matching specialization.
2973  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2974 
2975  // C++ [temp.class.spec.match]p1:
2976  // When a class template is used in a context that requires an
2977  // instantiation of the class, it is necessary to determine
2978  // whether the instantiation is to be generated using the primary
2979  // template or one of the partial specializations. This is done by
2980  // matching the template arguments of the class template
2981  // specialization with the template argument lists of the partial
2982  // specializations.
2983  typedef PartialSpecMatchResult MatchResult;
2986  Template->getPartialSpecializations(PartialSpecs);
2987  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2988  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2989  ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2990  TemplateDeductionInfo Info(FailedCandidates.getLocation());
2992  Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2993  // Store the failed-deduction information for use in diagnostics, later.
2994  // TODO: Actually use the failed-deduction info?
2995  FailedCandidates.addCandidate().set(
2996  DeclAccessPair::make(Template, AS_public), Partial,
2998  (void)Result;
2999  } else {
3000  Matched.push_back(PartialSpecMatchResult());
3001  Matched.back().Partial = Partial;
3002  Matched.back().Args = Info.take();
3003  }
3004  }
3005 
3006  // If we're dealing with a member template where the template parameters
3007  // have been instantiated, this provides the original template parameters
3008  // from which the member template's parameters were instantiated.
3009 
3010  if (Matched.size() >= 1) {
3011  SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3012  if (Matched.size() == 1) {
3013  // -- If exactly one matching specialization is found, the
3014  // instantiation is generated from that specialization.
3015  // We don't need to do anything for this.
3016  } else {
3017  // -- If more than one matching specialization is found, the
3018  // partial order rules (14.5.4.2) are used to determine
3019  // whether one of the specializations is more specialized
3020  // than the others. If none of the specializations is more
3021  // specialized than all of the other matching
3022  // specializations, then the use of the class template is
3023  // ambiguous and the program is ill-formed.
3024  for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3025  PEnd = Matched.end();
3026  P != PEnd; ++P) {
3028  P->Partial, Best->Partial, PointOfInstantiation) ==
3029  P->Partial)
3030  Best = P;
3031  }
3032 
3033  // Determine if the best partial specialization is more specialized than
3034  // the others.
3035  bool Ambiguous = false;
3036  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3037  PEnd = Matched.end();
3038  P != PEnd; ++P) {
3039  if (P != Best && S.getMoreSpecializedPartialSpecialization(
3040  P->Partial, Best->Partial,
3041  PointOfInstantiation) != Best->Partial) {
3042  Ambiguous = true;
3043  break;
3044  }
3045  }
3046 
3047  if (Ambiguous) {
3048  // Partial ordering did not produce a clear winner. Complain.
3049  Inst.Clear();
3050  ClassTemplateSpec->setInvalidDecl();
3051  S.Diag(PointOfInstantiation,
3052  diag::err_partial_spec_ordering_ambiguous)
3053  << ClassTemplateSpec;
3054 
3055  // Print the matching partial specializations.
3056  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3057  PEnd = Matched.end();
3058  P != PEnd; ++P)
3059  S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3061  P->Partial->getTemplateParameters(), *P->Args);
3062 
3063  return nullptr;
3064  }
3065  }
3066 
3067  ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3068  } else {
3069  // -- If no matches are found, the instantiation is generated
3070  // from the primary template.
3071  }
3072  }
3073 
3074  CXXRecordDecl *Pattern = nullptr;
3075  Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3076  if (auto *PartialSpec =
3077  Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3078  // Instantiate using the best class template partial specialization.
3079  while (PartialSpec->getInstantiatedFromMember()) {
3080  // If we've found an explicit specialization of this class template,
3081  // stop here and use that as the pattern.
3082  if (PartialSpec->isMemberSpecialization())
3083  break;
3084 
3085  PartialSpec = PartialSpec->getInstantiatedFromMember();
3086  }
3087  Pattern = PartialSpec;
3088  } else {
3089  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3090  while (Template->getInstantiatedFromMemberTemplate()) {
3091  // If we've found an explicit specialization of this class template,
3092  // stop here and use that as the pattern.
3093  if (Template->isMemberSpecialization())
3094  break;
3095 
3096  Template = Template->getInstantiatedFromMemberTemplate();
3097  }
3098  Pattern = Template->getTemplatedDecl();
3099  }
3100 
3101  return Pattern;
3102 }
3103 
3105  SourceLocation PointOfInstantiation,
3106  ClassTemplateSpecializationDecl *ClassTemplateSpec,
3107  TemplateSpecializationKind TSK, bool Complain) {
3108  // Perform the actual instantiation on the canonical declaration.
3109  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3110  ClassTemplateSpec->getCanonicalDecl());
3111  if (ClassTemplateSpec->isInvalidDecl())
3112  return true;
3113 
3115  *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
3116  if (!Pattern)
3117  return true;
3118 
3119  return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
3120  getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
3121  Complain);
3122 }
3123 
3124 /// Instantiates the definitions of all of the member
3125 /// of the given class, which is an instantiation of a class template
3126 /// or a member class of a template.
3127 void
3129  CXXRecordDecl *Instantiation,
3130  const MultiLevelTemplateArgumentList &TemplateArgs,
3132  // FIXME: We need to notify the ASTMutationListener that we did all of these
3133  // things, in case we have an explicit instantiation definition in a PCM, a
3134  // module, or preamble, and the declaration is in an imported AST.
3135  assert(
3138  (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3139  "Unexpected template specialization kind!");
3140  for (auto *D : Instantiation->decls()) {
3141  bool SuppressNew = false;
3142  if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3143  if (FunctionDecl *Pattern =
3144  Function->getInstantiatedFromMemberFunction()) {
3145 
3146  if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3147  continue;
3148 
3149  MemberSpecializationInfo *MSInfo =
3150  Function->getMemberSpecializationInfo();
3151  assert(MSInfo && "No member specialization information?");
3152  if (MSInfo->getTemplateSpecializationKind()
3154  continue;
3155 
3156  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3157  Function,
3159  MSInfo->getPointOfInstantiation(),
3160  SuppressNew) ||
3161  SuppressNew)
3162  continue;
3163 
3164  // C++11 [temp.explicit]p8:
3165  // An explicit instantiation definition that names a class template
3166  // specialization explicitly instantiates the class template
3167  // specialization and is only an explicit instantiation definition
3168  // of members whose definition is visible at the point of
3169  // instantiation.
3170  if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
3171  continue;
3172 
3173  Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3174 
3175  if (Function->isDefined()) {
3176  // Let the ASTConsumer know that this function has been explicitly
3177  // instantiated now, and its linkage might have changed.
3179  } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3180  InstantiateFunctionDefinition(PointOfInstantiation, Function);
3181  } else if (TSK == TSK_ImplicitInstantiation) {
3183  std::make_pair(Function, PointOfInstantiation));
3184  }
3185  }
3186  } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3187  if (isa<VarTemplateSpecializationDecl>(Var))
3188  continue;
3189 
3190  if (Var->isStaticDataMember()) {
3191  if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3192  continue;
3193 
3194  MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3195  assert(MSInfo && "No member specialization information?");
3196  if (MSInfo->getTemplateSpecializationKind()
3198  continue;
3199 
3200  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3201  Var,
3203  MSInfo->getPointOfInstantiation(),
3204  SuppressNew) ||
3205  SuppressNew)
3206  continue;
3207 
3209  // C++0x [temp.explicit]p8:
3210  // An explicit instantiation definition that names a class template
3211  // specialization explicitly instantiates the class template
3212  // specialization and is only an explicit instantiation definition
3213  // of members whose definition is visible at the point of
3214  // instantiation.
3215  if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
3216  continue;
3217 
3218  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3219  InstantiateVariableDefinition(PointOfInstantiation, Var);
3220  } else {
3221  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3222  }
3223  }
3224  } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3225  if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3226  continue;
3227 
3228  // Always skip the injected-class-name, along with any
3229  // redeclarations of nested classes, since both would cause us
3230  // to try to instantiate the members of a class twice.
3231  // Skip closure types; they'll get instantiated when we instantiate
3232  // the corresponding lambda-expression.
3233  if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3234  Record->isLambda())
3235  continue;
3236 
3237  MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3238  assert(MSInfo && "No member specialization information?");
3239 
3240  if (MSInfo->getTemplateSpecializationKind()
3242  continue;
3243 
3244  if (Context.getTargetInfo().getTriple().isOSWindows() &&
3246  // On Windows, explicit instantiation decl of the outer class doesn't
3247  // affect the inner class. Typically extern template declarations are
3248  // used in combination with dll import/export annotations, but those
3249  // are not propagated from the outer class templates to inner classes.
3250  // Therefore, do not instantiate inner classes on this platform, so
3251  // that users don't end up with undefined symbols during linking.
3252  continue;
3253  }
3254 
3255  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3256  Record,
3258  MSInfo->getPointOfInstantiation(),
3259  SuppressNew) ||
3260  SuppressNew)
3261  continue;
3262 
3263  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3264  assert(Pattern && "Missing instantiated-from-template information");
3265 
3266  if (!Record->getDefinition()) {
3267  if (!Pattern->getDefinition()) {
3268  // C++0x [temp.explicit]p8:
3269  // An explicit instantiation definition that names a class template
3270  // specialization explicitly instantiates the class template
3271  // specialization and is only an explicit instantiation definition
3272  // of members whose definition is visible at the point of
3273  // instantiation.
3275  MSInfo->setTemplateSpecializationKind(TSK);
3276  MSInfo->setPointOfInstantiation(PointOfInstantiation);
3277  }
3278 
3279  continue;
3280  }
3281 
3282  InstantiateClass(PointOfInstantiation, Record, Pattern,
3283  TemplateArgs,
3284  TSK);
3285  } else {
3287  Record->getTemplateSpecializationKind() ==
3289  Record->setTemplateSpecializationKind(TSK);
3290  MarkVTableUsed(PointOfInstantiation, Record, true);
3291  }
3292  }
3293 
3294  Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3295  if (Pattern)
3296  InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3297  TSK);
3298  } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3299  MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3300  assert(MSInfo && "No member specialization information?");
3301 
3302  if (MSInfo->getTemplateSpecializationKind()
3304  continue;
3305 
3307  PointOfInstantiation, TSK, Enum,
3309  MSInfo->getPointOfInstantiation(), SuppressNew) ||
3310  SuppressNew)
3311  continue;
3312 
3313  if (Enum->getDefinition())
3314  continue;
3315 
3316  EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3317  assert(Pattern && "Missing instantiated-from-template information");
3318 
3320  if (!Pattern->getDefinition())
3321  continue;
3322 
3323  InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3324  } else {
3325  MSInfo->setTemplateSpecializationKind(TSK);
3326  MSInfo->setPointOfInstantiation(PointOfInstantiation);
3327  }
3328  } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3329  // No need to instantiate in-class initializers during explicit
3330  // instantiation.
3331  if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
3332  CXXRecordDecl *ClassPattern =
3333  Instantiation->getTemplateInstantiationPattern();
3335  ClassPattern->lookup(Field->getDeclName());
3336  FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
3337  InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3338  TemplateArgs);
3339  }
3340  }
3341  }
3342 }
3343 
3344 /// Instantiate the definitions of all of the members of the
3345 /// given class template specialization, which was named as part of an
3346 /// explicit instantiation.
3347 void
3349  SourceLocation PointOfInstantiation,
3350  ClassTemplateSpecializationDecl *ClassTemplateSpec,
3352  // C++0x [temp.explicit]p7:
3353  // An explicit instantiation that names a class template
3354  // specialization is an explicit instantion of the same kind
3355  // (declaration or definition) of each of its members (not
3356  // including members inherited from base classes) that has not
3357  // been previously explicitly specialized in the translation unit
3358  // containing the explicit instantiation, except as described
3359  // below.
3360  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3361  getTemplateInstantiationArgs(ClassTemplateSpec),
3362  TSK);
3363 }
3364 
3365 StmtResult
3367  if (!S)
3368  return S;
3369 
3370  TemplateInstantiator Instantiator(*this, TemplateArgs,
3371  SourceLocation(),
3372  DeclarationName());
3373  return Instantiator.TransformStmt(S);
3374 }
3375 
3378  const MultiLevelTemplateArgumentList &TemplateArgs,
3379  TemplateArgumentListInfo &Out) {
3380  TemplateInstantiator Instantiator(*this, TemplateArgs,
3381  SourceLocation(),
3382  DeclarationName());
3383  return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(),
3384  Out);
3385 }
3386 
3387 ExprResult
3389  if (!E)
3390  return E;
3391 
3392  TemplateInstantiator Instantiator(*this, TemplateArgs,
3393  SourceLocation(),
3394  DeclarationName());
3395  return Instantiator.TransformExpr(E);
3396 }
3397 
3399  const MultiLevelTemplateArgumentList &TemplateArgs,
3400  bool CXXDirectInit) {
3401  TemplateInstantiator Instantiator(*this, TemplateArgs,
3402  SourceLocation(),
3403  DeclarationName());
3404  return Instantiator.TransformInitializer(Init, CXXDirectInit);
3405 }
3406 
3407 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
3408  const MultiLevelTemplateArgumentList &TemplateArgs,
3409  SmallVectorImpl<Expr *> &Outputs) {
3410  if (Exprs.empty())
3411  return false;
3412 
3413  TemplateInstantiator Instantiator(*this, TemplateArgs,
3414  SourceLocation(),
3415  DeclarationName());
3416  return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
3417  IsCall, Outputs);
3418 }
3419 
3422  const MultiLevelTemplateArgumentList &TemplateArgs) {
3423  if (!NNS)
3424  return NestedNameSpecifierLoc();
3425 
3426  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
3427  DeclarationName());
3428  return Instantiator.TransformNestedNameSpecifierLoc(NNS);
3429 }
3430 
3431 /// Do template substitution on declaration name info.
3434  const MultiLevelTemplateArgumentList &TemplateArgs) {
3435  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
3436  NameInfo.getName());
3437  return Instantiator.TransformDeclarationNameInfo(NameInfo);
3438 }
3439 
3442  TemplateName Name, SourceLocation Loc,
3443  const MultiLevelTemplateArgumentList &TemplateArgs) {
3444  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3445  DeclarationName());
3446  CXXScopeSpec SS;
3447  SS.Adopt(QualifierLoc);
3448  return Instantiator.TransformTemplateName(SS, Name, Loc);
3449 }
3450 
3451 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
3453  const MultiLevelTemplateArgumentList &TemplateArgs) {
3454  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3455  DeclarationName());
3456 
3457  return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
3458 }
3459 
3460 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
3461  // When storing ParmVarDecls in the local instantiation scope, we always
3462  // want to use the ParmVarDecl from the canonical function declaration,
3463  // since the map is then valid for any redeclaration or definition of that
3464  // function.
3465  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
3466  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
3467  unsigned i = PV->getFunctionScopeIndex();
3468  // This parameter might be from a freestanding function type within the
3469  // function and isn't necessarily referring to one of FD's parameters.
3470  if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
3471  return FD->getCanonicalDecl()->getParamDecl(i);
3472  }
3473  }
3474  return D;
3475 }
3476 
3477 
3478 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3480  D = getCanonicalParmVarDecl(D);
3481  for (LocalInstantiationScope *Current = this; Current;
3482  Current = Current->Outer) {
3483 
3484  // Check if we found something within this scope.
3485  const Decl *CheckD = D;
3486  do {
3487  LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
3488  if (Found != Current->LocalDecls.end())
3489  return &Found->second;
3490 
3491  // If this is a tag declaration, it's possible that we need to look for
3492  // a previous declaration.
3493  if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
3494  CheckD = Tag->getPreviousDecl();
3495  else
3496  CheckD = nullptr;
3497  } while (CheckD);
3498 
3499  // If we aren't combined with our outer scope, we're done.
3500  if (!Current->CombineWithOuterScope)
3501  break;
3502  }
3503 
3504  // If we're performing a partial substitution during template argument
3505  // deduction, we may not have values for template parameters yet.
3506  if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3507  isa<TemplateTemplateParmDecl>(D))
3508  return nullptr;
3509 
3510  // Local types referenced prior to definition may require instantiation.
3511  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3512  if (RD->isLocalClass())
3513  return nullptr;
3514 
3515  // Enumeration types referenced prior to definition may appear as a result of
3516  // error recovery.
3517  if (isa<EnumDecl>(D))
3518  return nullptr;
3519 
3520  // If we didn't find the decl, then we either have a sema bug, or we have a
3521  // forward reference to a label declaration. Return null to indicate that
3522  // we have an uninstantiated label.
3523  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
3524  return nullptr;
3525 }
3526 
3528  D = getCanonicalParmVarDecl(D);
3529  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3530  if (Stored.isNull()) {
3531 #ifndef NDEBUG
3532  // It should not be present in any surrounding scope either.
3533  LocalInstantiationScope *Current = this;
3534  while (Current->CombineWithOuterScope && Current->Outer) {
3535  Current = Current->Outer;
3536  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3537  "Instantiated local in inner and outer scopes");
3538  }
3539 #endif
3540  Stored = Inst;
3541  } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
3542  Pack->push_back(cast<VarDecl>(Inst));
3543  } else {
3544  assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
3545  }
3546 }
3547 
3549  VarDecl *Inst) {
3550  D = getCanonicalParmVarDecl(D);
3551  DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3552  Pack->push_back(Inst);
3553 }
3554 
3556 #ifndef NDEBUG
3557  // This should be the first time we've been told about this decl.
3558  for (LocalInstantiationScope *Current = this;
3559  Current && Current->CombineWithOuterScope; Current = Current->Outer)
3560  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3561  "Creating local pack after instantiation of local");
3562 #endif
3563 
3564  D = getCanonicalParmVarDecl(D);
3565  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3566  DeclArgumentPack *Pack = new DeclArgumentPack;
3567  Stored = Pack;
3568  ArgumentPacks.push_back(Pack);
3569 }
3570 
3572  const TemplateArgument *ExplicitArgs,
3573  unsigned NumExplicitArgs) {
3574  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3575  "Already have a partially-substituted pack");
3576  assert((!PartiallySubstitutedPack
3577  || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3578  "Wrong number of arguments in partially-substituted pack");
3579  PartiallySubstitutedPack = Pack;
3580  ArgsInPartiallySubstitutedPack = ExplicitArgs;
3581  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3582 }
3583 
3585  const TemplateArgument **ExplicitArgs,
3586  unsigned *NumExplicitArgs) const {
3587  if (ExplicitArgs)
3588  *ExplicitArgs = nullptr;
3589  if (NumExplicitArgs)
3590  *NumExplicitArgs = 0;
3591 
3592  for (const LocalInstantiationScope *Current = this; Current;
3593  Current = Current->Outer) {
3594  if (Current->PartiallySubstitutedPack) {
3595  if (ExplicitArgs)
3596  *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3597  if (NumExplicitArgs)
3598  *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3599 
3600  return Current->PartiallySubstitutedPack;
3601  }
3602 
3603  if (!Current->CombineWithOuterScope)
3604  break;
3605  }
3606 
3607  return nullptr;
3608 }
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:5532
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
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.
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic...
Definition: Diagnostic.h:575
void ActOnFinishDelayedMemberInitializers(Decl *Record)
Represents a type that was referred to using an elaborated type keyword, e.g., struct S...
Definition: Type.h:5285
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1628
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:8050
Represents a function declaration or definition.
Definition: Decl.h:1783
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:524
no exception specification
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:502
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
QualType getPointeeType() const
Definition: Type.h:2627
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1248
A (possibly-)qualified type.
Definition: Type.h:654
ASTConsumer & Consumer
Definition: Sema.h:386
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:7752
void InstantiatedLocal(const Decl *D, Decl *Inst)
base_class_range bases()
Definition: DeclCXX.h:587
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:581
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:227
A requires-expression requirement which queries the validity and properties of an expression (&#39;simple...
Definition: ExprConcepts.h:253
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained)...
Definition: Sema.h:8192
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4366
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:2862
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:133
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:8085
Stmt - This represents one statement.
Definition: Stmt.h:66
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
Provides information about an attempted template argument deduction, whose success or failure was des...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:994
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1029
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:5049
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:86
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
QualType getUnderlyingType() const
Definition: Type.h:4285
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1411
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Defines the C++ template declaration subclasses.
StringRef P
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:8135
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:960
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation. ...
Definition: Sema.h:8146
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2918
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:8592
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1300
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2889
Declaration of a variable template.
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:63
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:138
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:707
A container of type source information.
Definition: Type.h:6227
bool SubstExprs(ArrayRef< Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr *> &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
IdentKind getIdentKind() const
Definition: Expr.h:1951
bool isStackNearlyExhausted()
Determine whether the stack is nearly exhausted.
Definition: Stack.cpp:46
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
We are instantiating a default argument for a template parameter.
Definition: Sema.h:7999
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:4694
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore, should not be counted as part of the instantiation depth.
Definition: Sema.h:8176
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:233
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:2869
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:228
QualType getElementType() const
Definition: Type.h:2910
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:508
This file provides some common utility functions for processing Lambda related AST Constructs...
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:124
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
Definition: ExprConcepts.h:381
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:574
unsigned getDepth() const
Get the nesting depth of the template parameter.
RAII object that enters a new expression evaluation context.
Definition: Sema.h:12029
Represents a variable declaration or definition.
Definition: Decl.h:820
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1792
MatchFinder::MatchResult MatchResult
DiagnosticsEngine & Diags
Definition: Sema.h:387
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:2487
void ActOnFinishCXXNonNestedClass()
bool hasInheritedDefaultArg() const
Definition: Decl.h:1725
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2033
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Represents a variable template specialization, which refers to a variable template with a given set o...
RAII object used to temporarily allow the C++ &#39;this&#39; expression to be used, with the given qualifiers...
Definition: Sema.h:5616
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:603
reference front() const
Definition: DeclBase.h:1242
bool isInvalidDecl() const
Definition: DeclBase.h:553
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:69
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:7987
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:211
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:644
Represents a parameter to a function.
Definition: Decl.h:1595
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:314
iterator begin() const
Definition: ExprCXX.h:4374
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:8094
The collection of all-type qualifiers we support.
Definition: Type.h:143
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1440
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1711
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:335
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
Represents a struct/union/class.
Definition: Decl.h:3748
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:99
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:272
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
QualType getOriginalType() const
Definition: Type.h:2678
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...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:8508
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:470
TemplateName getNameToSubstitute() const
Get the template name to substitute when this template name is used as a template template argument...
QualType getPointeeType() const
Definition: Type.h:2731
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:329
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2747
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
A C++ nested-name-specifier augmented with source location information.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1195
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:275
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:14655
Represents a member of a struct/union/class.
Definition: Decl.h:2729
The current expression is potentially evaluated at run time, which means that code may be generated t...
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition: Template.h:122
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
NonTypeTemplateParmDecl * getParameter() const
Definition: ExprCXX.h:4243
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1652
An operation on a type.
Definition: TypeVisitor.h:64
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:780
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation, for substitutions of prior template arguments.
Definition: Sema.h:8090
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4154
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
bool isReferenceType() const
Definition: Type.h:6516
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:855
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:195
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4269
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:536
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:268
Describes a module or submodule.
Definition: Module.h:64
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:125
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:8032
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4378
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:527
PtrTy get() const
Definition: Ownership.h:170
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
TemplateArgument getArgumentPack() const
Retrieve the template argument pack containing the substituted template arguments.
Definition: ExprCXX.cpp:1626
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:4312
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SourceLocation getParameterPackLocation() const
Retrieve the location of the parameter pack name.
Definition: ExprCXX.h:4300
A convenient class for passing around template argument information.
Definition: TemplateBase.h:554
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:8039
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:888
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:274
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:414
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:840
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation...
Definition: Type.h:4266
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:8151
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1896
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:833
SourceLocation RAngleLoc
The source location of the right angle bracket (&#39;>&#39;).
Definition: TemplateBase.h:617
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced...
Definition: Sema.h:8184
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:8082
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization...
Definition: Decl.h:3729
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template, alias template, or a member thereof.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:492
const TemplateArgument * getArgs() const
Retrieve the template arguments.
Definition: Type.h:5062
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1709
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:436
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:828
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1818
const LangOptions & getLangOpts() const
Definition: Sema.h:1324
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:176
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1202
void setLocStart(SourceLocation L)
Definition: Decl.h:3057
QualType getPointeeTypeAsWritten() const
Definition: Type.h:2769
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
QualType getElementType() const
Definition: Type.h:3211
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:8206
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:415
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3195
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
A helper class for building up ExtParameterInfos.
Definition: Sema.h:8617
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1612
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1328
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:8450
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
We are substituting explicit template arguments provided for a function template. ...
Definition: Sema.h:8008
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:336
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.
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:198
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1700
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:65
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl *> Params)
Definition: ExprCXX.cpp:1643
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...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
SourceLocation getLocation() const
Definition: Expr.h:1255
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:16551
We are instantiating a template declaration.
Definition: Sema.h:7992
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:263
Added for Template instantiation observation.
Definition: Sema.h:8075
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations, which must be passed to InstantiateClassTemplatePartialSpecialization once the class definition has been completed.
Definition: Template.h:520
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:421
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1642
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost=nullptr, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:619
This represents one expression.
Definition: Expr.h:108
Defines the clang::LangOptions interface.
StringRef getKindName() const
Definition: Decl.h:3394
SourceLocation End
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:5224
int Id
Definition: ASTDiff.cpp:190
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6147
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror...
Definition: Diagnostic.h:757
Declaration of a template type parameter.
unsigned getIndex() const
Definition: Type.h:4691
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:620
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:8382
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:8015
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5206
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:67
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
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...
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:558
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1725
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:8167
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isFileContext() const
Definition: DeclBase.h:1854
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional< unsigned > NumExpansions, bool ExpectParameterPack)
DeclContext * getDeclContext()
Definition: DeclBase.h:438
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:533
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member, and after instantiating an in-class initializer in a class template.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:63
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a C++ template name within the type system.
Definition: TemplateName.h:191
EnumDecl * getDefinition() const
Definition: Decl.h:3582
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this...
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy)
Print a template argument list, including the &#39;<&#39; and &#39;>&#39; enclosing the template arguments.
int Depth
Definition: ASTDiff.cpp:190
QualType getType() const
Definition: Expr.h:137
TypeSourceInfo * getType() const
Definition: ExprConcepts.h:240
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:2611
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:64
bool isInvalid() const
Definition: Ownership.h:166
void setLocation(SourceLocation L)
Definition: DeclBase.h:430
Represents a GCC generic vector type.
Definition: Type.h:3235
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:1678
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:4209
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
ValueDecl * getDecl()
Definition: Expr.h:1247
SourceLocation getLocation() const
Definition: Expr.h:1955
bool isUsable() const
Definition: Ownership.h:167
We are instantiating a requirement of a requires expression.
Definition: Sema.h:8035
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:181
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:295
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation. ...
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4338
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all otuer scopes, down to the given outermost scope. ...
Definition: Template.h:360
virtual void printName(raw_ostream &os) const
Definition: Decl.cpp:1551
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
We are declaring an implicit special member function.
Definition: Sema.h:8042
#define false
Definition: stdbool.h:17
Kind
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3813
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1151
A stack object to be created when performing template instantiation.
Definition: Sema.h:8243
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3975
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs)
Encodes a location in the source.
Sugar for parentheses used when specifying types.
Definition: Type.h:2584
QualType getReturnType() const
Definition: Type.h:3680
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:8028
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2166
void setBraceRange(SourceRange R)
Definition: Decl.h:3301
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:8113
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:134
DeclarationName getName() const
getName - Returns the embedded declaration name.
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3219
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3403
TemplateParameterList * SubstTemplateParams(TemplateParameterList *List)
Instantiates a nested template parameter list in the current instantiation context.
QualType getElementType() const
Definition: Type.h:3270
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set...
Definition: Decl.h:2876
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:7989
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4381
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:8024
bool isParameterPack() const
Definition: Type.h:4692
SourceLocation getNoexceptLoc() const
Definition: ExprConcepts.h:363
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:359
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:4802
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
static const Decl * getCanonicalParmVarDecl(const Decl *D)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
QualType getInnerType() const
Definition: Type.h:2597
void setTagKind(TagKind TK)
Definition: Decl.h:3402
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:8138
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1713
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:193
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:3763
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema&#39;s representation of template deduction information to the form used in overload-can...
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:145
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1417
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:163
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition: Template.h:109
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:2657
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1729
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:573
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(DeclContext *DC)
Definition: ASTLambda.h:67
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2156
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:224
Represents a pack expansion of types.
Definition: Type.h:5511
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:653
SourceLocation getLocation() const
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
Definition: TemplateBase.h:626
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization, which was named as part of an explicit instantiation.
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4337
Represents a template argument.
Definition: TemplateBase.h:50
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons...
Definition: Type.h:2662
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument. ...
TagTypeKind
The kind of a tag type.
Definition: Type.h:5187
bool isNull() const
Determine whether this template name is NULL.
Dataflow Directional Tag Classes.
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1672
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:8200
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: Sema.h:8100
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1903
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:402
static std::string getName(const CallEvent &Call)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:453
NonTypeTemplateParmDecl * getParameterPack() const
Retrieve the non-type template parameter pack being substituted.
Definition: ExprCXX.h:4297
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:132
We are instantiating a default argument for a function.
Definition: Sema.h:8004
QualType RebuildElaboratedType(SourceLocation KeywordLoc, ElaboratedTypeKeyword Keyword, NestedNameSpecifierLoc QualifierLoc, QualType Named)
Build a new qualified name type.
delayed_partial_spec_iterator delayed_partial_spec_end()
Return an iterator to the end of the set of "delayed" partial specializations, which must be passed t...
Definition: Template.h:532
Interesting information about a specific parameter that can&#39;t simply be reflected in parameter&#39;s type...
Definition: Type.h:3448
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:189
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1773
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4373
The name of a declaration.
Expr * getDefaultArg()
Definition: Decl.cpp:2710
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void setInstantiationOfMemberFunction(FunctionDecl *FD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member function FD.
Definition: Decl.h:2566
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:8118
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:1671
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)...
Represents an enum.
Definition: Decl.h:3481
SourceLocation LAngleLoc
The source location of the left angle bracket (&#39;<&#39;).
Definition: TemplateBase.h:614
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2833
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack...
Definition: Decl.cpp:2464
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4369
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:175
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set...
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:339
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:13294
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:237
We are declaring an implicit &#39;operator==&#39; for a defaulted &#39;operator<=>&#39;.
Definition: Sema.h:8046
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
QualType getModifiedType() const
Definition: Type.h:4575
iterator end() const
Definition: ExprCXX.h:4375
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
Pointer to a block type.
Definition: Type.h:2716
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:449
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
unsigned getNumArgs() const
Retrieve the number of template arguments.
Definition: Type.h:5067
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1721
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2752
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:185
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:700
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:1195
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2750
The template argument is a type.
Definition: TemplateBase.h:59
Holds information about the various types of exception specification.
Definition: Type.h:3811
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:514
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
The template argument is actually a parameter pack.
Definition: TemplateBase.h:90
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2915
Represents a base class of a C++ class.
Definition: DeclCXX.h:145
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:8079
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2305
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:8386
A template argument list.
Definition: DeclTemplate.h:239
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:760
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:234
unsigned getDepth() const
Definition: Type.h:4690
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4550
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\, const ASTContext *Context=nullptr) const
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
bool isVoidType() const
Definition: Type.h:6777
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier *> Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:402
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA)
Definition: Template.h:497
void Clear()
Note that we have finished instantiating this template.
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:622
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:5325
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition: Template.h:511
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:397
Declaration of a class template.
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:129
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:8069
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:263
SourceLocation getNameLoc() const
Definition: TypeLoc.h:523
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:8020
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:250
ExprResult ExprError()
Definition: Ownership.h:279
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1237
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2150
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:256
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1171
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4996
Defines utilities for dealing with stack allocation and stack space.
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
QualType getType() const
Definition: Decl.h:630
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:129
Wrapper for template type parameters.
Definition: TypeLoc.h:734
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:385
This represents a decl that may have a name.
Definition: Decl.h:223
bool isTranslationUnit() const
Definition: DeclBase.h:1859
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:77
NamedDecl * getAsNamedDecl(TemplateParameter P)
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate members of the class templa...
No keyword precedes the qualified type name.
Definition: Type.h:5227
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:280
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:662
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:667
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:199
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:714
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3843
Declaration of a template function.
Definition: DeclTemplate.h:977
Attr - This represents one attribute.
Definition: Attr.h:45
SourceLocation getLocation() const
Definition: DeclBase.h:429
QualType getPointeeType() const
Definition: Type.h:2853
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6238
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1790
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:8481
A RAII object to temporarily push a declaration context.
Definition: Sema.h:797
static CXXRecordDecl * getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
const ReturnTypeRequirement & getReturnTypeRequirement() const
Definition: ExprConcepts.h:371