clang  5.0.0
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements C++ template instantiation.
10 //
11 //===----------------------------------------------------------------------===/
12 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
22 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Template.h"
28 
29 using namespace clang;
30 using namespace sema;
31 
32 //===----------------------------------------------------------------------===/
33 // Template Instantiation Support
34 //===----------------------------------------------------------------------===/
35 
36 /// \brief Retrieve the template argument list(s) that should be used to
37 /// instantiate the definition of the given declaration.
38 ///
39 /// \param D the declaration for which we are computing template instantiation
40 /// arguments.
41 ///
42 /// \param Innermost if non-NULL, the innermost template argument list.
43 ///
44 /// \param RelativeToPrimary true if we should get the template
45 /// arguments relative to the primary template, even when we're
46 /// dealing with a specialization. This is only relevant for function
47 /// template specializations.
48 ///
49 /// \param Pattern If non-NULL, indicates the pattern from which we will be
50 /// instantiating the definition of the given declaration, \p D. This is
51 /// used to determine the proper set of template instantiation arguments for
52 /// friend function template specializations.
55  const TemplateArgumentList *Innermost,
56  bool RelativeToPrimary,
57  const FunctionDecl *Pattern) {
58  // Accumulate the set of template argument lists in this structure.
60 
61  if (Innermost)
62  Result.addOuterTemplateArguments(Innermost);
63 
64  DeclContext *Ctx = dyn_cast<DeclContext>(D);
65  if (!Ctx) {
66  Ctx = D->getDeclContext();
67 
68  // Add template arguments from a variable template instantiation.
70  dyn_cast<VarTemplateSpecializationDecl>(D)) {
71  // We're done when we hit an explicit specialization.
72  if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73  !isa<VarTemplatePartialSpecializationDecl>(Spec))
74  return Result;
75 
76  Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77 
78  // If this variable template specialization was instantiated from a
79  // specialized member that is a variable template, we're done.
80  assert(Spec->getSpecializedTemplate() && "No variable template?");
81  llvm::PointerUnion<VarTemplateDecl*,
85  Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86  if (Partial->isMemberSpecialization())
87  return Result;
88  } else {
89  VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90  if (Tmpl->isMemberSpecialization())
91  return Result;
92  }
93  }
94 
95  // If we have a template template parameter with translation unit context,
96  // then we're performing substitution into a default template argument of
97  // this template template parameter before we've constructed the template
98  // that will own this template template parameter. In this case, we
99  // use empty template parameter lists for all of the outer templates
100  // to avoid performing any substitutions.
101  if (Ctx->isTranslationUnit()) {
102  if (TemplateTemplateParmDecl *TTP
103  = dyn_cast<TemplateTemplateParmDecl>(D)) {
104  for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
106  return Result;
107  }
108  }
109  }
110 
111  while (!Ctx->isFileContext()) {
112  // Add template arguments from a class template instantiation.
114  = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115  // We're done when we hit an explicit specialization.
116  if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117  !isa<ClassTemplatePartialSpecializationDecl>(Spec))
118  break;
119 
120  Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
121 
122  // If this class template specialization was instantiated from a
123  // specialized member that is a class template, we're done.
124  assert(Spec->getSpecializedTemplate() && "No class template?");
125  if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126  break;
127  }
128  // Add template arguments from a function template specialization.
129  else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
130  if (!RelativeToPrimary &&
131  (Function->getTemplateSpecializationKind() ==
133  !Function->getClassScopeSpecializationPattern()))
134  break;
135 
136  if (const TemplateArgumentList *TemplateArgs
137  = Function->getTemplateSpecializationArgs()) {
138  // Add the template arguments for this specialization.
139  Result.addOuterTemplateArguments(TemplateArgs);
140 
141  // If this function was instantiated from a specialized member that is
142  // a function template, we're done.
143  assert(Function->getPrimaryTemplate() && "No function template?");
144  if (Function->getPrimaryTemplate()->isMemberSpecialization())
145  break;
146 
147  // If this function is a generic lambda specialization, we are done.
149  break;
150 
151  } else if (FunctionTemplateDecl *FunTmpl
152  = Function->getDescribedFunctionTemplate()) {
153  // Add the "injected" template arguments.
154  Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
155  }
156 
157  // If this is a friend declaration and it declares an entity at
158  // namespace scope, take arguments from its lexical parent
159  // instead of its semantic parent, unless of course the pattern we're
160  // instantiating actually comes from the file's context!
161  if (Function->getFriendObjectKind() &&
162  Function->getDeclContext()->isFileContext() &&
163  (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
164  Ctx = Function->getLexicalDeclContext();
165  RelativeToPrimary = false;
166  continue;
167  }
168  } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169  if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170  QualType T = ClassTemplate->getInjectedClassNameSpecialization();
171  const TemplateSpecializationType *TST =
172  cast<TemplateSpecializationType>(Context.getCanonicalType(T));
174  llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
175  if (ClassTemplate->isMemberSpecialization())
176  break;
177  }
178  }
179 
180  Ctx = Ctx->getParent();
181  RelativeToPrimary = false;
182  }
183 
184  return Result;
185 }
186 
188  switch (Kind) {
189  case TemplateInstantiation:
190  case ExceptionSpecInstantiation:
191  case DefaultTemplateArgumentInstantiation:
192  case DefaultFunctionArgumentInstantiation:
193  case ExplicitTemplateArgumentSubstitution:
194  case DeducedTemplateArgumentSubstitution:
195  case PriorTemplateArgumentSubstitution:
196  return true;
197 
198  case DefaultTemplateArgumentChecking:
199  case DeclaringSpecialMember:
200  case DefiningSynthesizedFunction:
201  return false;
202  }
203 
204  llvm_unreachable("Invalid SynthesisKind!");
205 }
206 
209  SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
210  Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
211  sema::TemplateDeductionInfo *DeductionInfo)
212  : SemaRef(SemaRef) {
213  // Don't allow further instantiation if a fatal error and an uncompilable
214  // error have occurred. Any diagnostics we might have raised will not be
215  // visible, and we do not need to construct a correct AST.
216  if (SemaRef.Diags.hasFatalErrorOccurred() &&
218  Invalid = true;
219  return;
220  }
221  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
222  if (!Invalid) {
224  Inst.Kind = Kind;
225  Inst.PointOfInstantiation = PointOfInstantiation;
226  Inst.Entity = Entity;
227  Inst.Template = Template;
228  Inst.TemplateArgs = TemplateArgs.data();
229  Inst.NumTemplateArgs = TemplateArgs.size();
230  Inst.DeductionInfo = DeductionInfo;
231  Inst.InstantiationRange = InstantiationRange;
232  SemaRef.pushCodeSynthesisContext(Inst);
233 
234  AlreadyInstantiating =
236  .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
237  .second;
238  }
239 }
240 
242  Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
243  SourceRange InstantiationRange)
244  : InstantiatingTemplate(SemaRef,
245  CodeSynthesisContext::TemplateInstantiation,
246  PointOfInstantiation, InstantiationRange, Entity) {}
247 
249  Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
250  ExceptionSpecification, SourceRange InstantiationRange)
252  SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
253  PointOfInstantiation, InstantiationRange, Entity) {}
254 
256  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
257  TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
258  SourceRange InstantiationRange)
260  SemaRef,
261  CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
262  PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
263  Template, TemplateArgs) {}
264 
266  Sema &SemaRef, SourceLocation PointOfInstantiation,
267  FunctionTemplateDecl *FunctionTemplate,
268  ArrayRef<TemplateArgument> TemplateArgs,
270  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
271  : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
272  InstantiationRange, FunctionTemplate, nullptr,
273  TemplateArgs, &DeductionInfo) {
274  assert(
277 }
278 
280  Sema &SemaRef, SourceLocation PointOfInstantiation,
281  TemplateDecl *Template,
282  ArrayRef<TemplateArgument> TemplateArgs,
283  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285  SemaRef,
286  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
287  PointOfInstantiation, InstantiationRange, Template, nullptr,
288  TemplateArgs, &DeductionInfo) {}
289 
291  Sema &SemaRef, SourceLocation PointOfInstantiation,
293  ArrayRef<TemplateArgument> TemplateArgs,
294  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
296  SemaRef,
297  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
298  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
299  TemplateArgs, &DeductionInfo) {}
300 
302  Sema &SemaRef, SourceLocation PointOfInstantiation,
304  ArrayRef<TemplateArgument> TemplateArgs,
305  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
307  SemaRef,
308  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
309  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
310  TemplateArgs, &DeductionInfo) {}
311 
313  Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
314  ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
316  SemaRef,
317  CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
318  PointOfInstantiation, InstantiationRange, Param, nullptr,
319  TemplateArgs) {}
320 
322  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
324  SourceRange InstantiationRange)
326  SemaRef,
327  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
328  PointOfInstantiation, InstantiationRange, Param, Template,
329  TemplateArgs) {}
330 
332  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
334  SourceRange InstantiationRange)
336  SemaRef,
337  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
338  PointOfInstantiation, InstantiationRange, Param, Template,
339  TemplateArgs) {}
340 
342  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
343  NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
344  SourceRange InstantiationRange)
346  SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
347  PointOfInstantiation, InstantiationRange, Param, Template,
348  TemplateArgs) {}
349 
353 
354  CodeSynthesisContexts.push_back(Ctx);
355 
356  if (!Ctx.isInstantiationRecord())
358 }
359 
361  auto &Active = CodeSynthesisContexts.back();
362  if (!Active.isInstantiationRecord()) {
363  assert(NonInstantiationEntries > 0);
365  }
366 
367  InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
368 
369  // Name lookup no longer looks in this template's defining module.
370  assert(CodeSynthesisContexts.size() >=
372  "forgot to remove a lookup module for a template instantiation");
373  if (CodeSynthesisContexts.size() ==
376  LookupModulesCache.erase(M);
378  }
379 
380  // If we've left the code synthesis context for the current context stack,
381  // stop remembering that we've emitted that stack.
382  if (CodeSynthesisContexts.size() ==
385 
386  CodeSynthesisContexts.pop_back();
387 }
388 
390  if (!Invalid) {
391  if (!AlreadyInstantiating) {
392  auto &Active = SemaRef.CodeSynthesisContexts.back();
393  SemaRef.InstantiatingSpecializations.erase(
394  std::make_pair(Active.Entity, Active.Kind));
395  }
396 
397  SemaRef.popCodeSynthesisContext();
398 
399  Invalid = true;
400  }
401 }
402 
403 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
404  SourceLocation PointOfInstantiation,
405  SourceRange InstantiationRange) {
406  assert(SemaRef.NonInstantiationEntries <=
407  SemaRef.CodeSynthesisContexts.size());
408  if ((SemaRef.CodeSynthesisContexts.size() -
409  SemaRef.NonInstantiationEntries)
410  <= SemaRef.getLangOpts().InstantiationDepth)
411  return false;
412 
413  SemaRef.Diag(PointOfInstantiation,
414  diag::err_template_recursion_depth_exceeded)
415  << SemaRef.getLangOpts().InstantiationDepth
416  << InstantiationRange;
417  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
418  << SemaRef.getLangOpts().InstantiationDepth;
419  return true;
420 }
421 
422 /// \brief Prints the current instantiation stack through a series of
423 /// notes.
425  // Determine which template instantiations to skip, if any.
426  unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
427  unsigned Limit = Diags.getTemplateBacktraceLimit();
428  if (Limit && Limit < CodeSynthesisContexts.size()) {
429  SkipStart = Limit / 2 + Limit % 2;
430  SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
431  }
432 
433  // FIXME: In all of these cases, we need to show the template arguments
434  unsigned InstantiationIdx = 0;
436  Active = CodeSynthesisContexts.rbegin(),
437  ActiveEnd = CodeSynthesisContexts.rend();
438  Active != ActiveEnd;
439  ++Active, ++InstantiationIdx) {
440  // Skip this instantiation?
441  if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
442  if (InstantiationIdx == SkipStart) {
443  // Note that we're skipping instantiations.
444  Diags.Report(Active->PointOfInstantiation,
445  diag::note_instantiation_contexts_suppressed)
446  << unsigned(CodeSynthesisContexts.size() - Limit);
447  }
448  continue;
449  }
450 
451  switch (Active->Kind) {
453  Decl *D = Active->Entity;
454  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
455  unsigned DiagID = diag::note_template_member_class_here;
456  if (isa<ClassTemplateSpecializationDecl>(Record))
457  DiagID = diag::note_template_class_instantiation_here;
458  Diags.Report(Active->PointOfInstantiation, DiagID)
459  << Record << Active->InstantiationRange;
460  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
461  unsigned DiagID;
462  if (Function->getPrimaryTemplate())
463  DiagID = diag::note_function_template_spec_here;
464  else
465  DiagID = diag::note_template_member_function_here;
466  Diags.Report(Active->PointOfInstantiation, DiagID)
467  << Function
468  << Active->InstantiationRange;
469  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
470  Diags.Report(Active->PointOfInstantiation,
471  VD->isStaticDataMember()?
472  diag::note_template_static_data_member_def_here
473  : diag::note_template_variable_def_here)
474  << VD
475  << Active->InstantiationRange;
476  } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
477  Diags.Report(Active->PointOfInstantiation,
478  diag::note_template_enum_def_here)
479  << ED
480  << Active->InstantiationRange;
481  } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
482  Diags.Report(Active->PointOfInstantiation,
483  diag::note_template_nsdmi_here)
484  << FD << Active->InstantiationRange;
485  } else {
486  Diags.Report(Active->PointOfInstantiation,
487  diag::note_template_type_alias_instantiation_here)
488  << cast<TypeAliasTemplateDecl>(D)
489  << Active->InstantiationRange;
490  }
491  break;
492  }
493 
495  TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
496  SmallVector<char, 128> TemplateArgsStr;
497  llvm::raw_svector_ostream OS(TemplateArgsStr);
498  Template->printName(OS);
500  OS, Active->template_arguments(), getPrintingPolicy());
501  Diags.Report(Active->PointOfInstantiation,
502  diag::note_default_arg_instantiation_here)
503  << OS.str()
504  << Active->InstantiationRange;
505  break;
506  }
507 
509  FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
510  Diags.Report(Active->PointOfInstantiation,
511  diag::note_explicit_template_arg_substitution_here)
512  << FnTmpl
514  Active->TemplateArgs,
515  Active->NumTemplateArgs)
516  << Active->InstantiationRange;
517  break;
518  }
519 
521  if (FunctionTemplateDecl *FnTmpl =
522  dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
523  Diags.Report(Active->PointOfInstantiation,
524  diag::note_function_template_deduction_instantiation_here)
525  << FnTmpl
526  << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
527  Active->TemplateArgs,
528  Active->NumTemplateArgs)
529  << Active->InstantiationRange;
530  } else {
531  bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
532  isa<VarTemplateSpecializationDecl>(Active->Entity);
533  bool IsTemplate = false;
534  TemplateParameterList *Params;
535  if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
536  IsTemplate = true;
537  Params = D->getTemplateParameters();
538  } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
539  Active->Entity)) {
540  Params = D->getTemplateParameters();
541  } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
542  Active->Entity)) {
543  Params = D->getTemplateParameters();
544  } else {
545  llvm_unreachable("unexpected template kind");
546  }
547 
548  Diags.Report(Active->PointOfInstantiation,
549  diag::note_deduced_template_arg_substitution_here)
550  << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
551  << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
552  Active->NumTemplateArgs)
553  << Active->InstantiationRange;
554  }
555  break;
556  }
557 
559  ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
560  FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
561 
562  SmallVector<char, 128> TemplateArgsStr;
563  llvm::raw_svector_ostream OS(TemplateArgsStr);
564  FD->printName(OS);
566  OS, Active->template_arguments(), getPrintingPolicy());
567  Diags.Report(Active->PointOfInstantiation,
568  diag::note_default_function_arg_instantiation_here)
569  << OS.str()
570  << Active->InstantiationRange;
571  break;
572  }
573 
575  NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
576  std::string Name;
577  if (!Parm->getName().empty())
578  Name = std::string(" '") + Parm->getName().str() + "'";
579 
580  TemplateParameterList *TemplateParams = nullptr;
581  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
582  TemplateParams = Template->getTemplateParameters();
583  else
584  TemplateParams =
585  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
586  ->getTemplateParameters();
587  Diags.Report(Active->PointOfInstantiation,
588  diag::note_prior_template_arg_substitution)
589  << isa<TemplateTemplateParmDecl>(Parm)
590  << Name
591  << getTemplateArgumentBindingsText(TemplateParams,
592  Active->TemplateArgs,
593  Active->NumTemplateArgs)
594  << Active->InstantiationRange;
595  break;
596  }
597 
599  TemplateParameterList *TemplateParams = nullptr;
600  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
601  TemplateParams = Template->getTemplateParameters();
602  else
603  TemplateParams =
604  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
605  ->getTemplateParameters();
606 
607  Diags.Report(Active->PointOfInstantiation,
608  diag::note_template_default_arg_checking)
609  << getTemplateArgumentBindingsText(TemplateParams,
610  Active->TemplateArgs,
611  Active->NumTemplateArgs)
612  << Active->InstantiationRange;
613  break;
614  }
615 
617  Diags.Report(Active->PointOfInstantiation,
618  diag::note_template_exception_spec_instantiation_here)
619  << cast<FunctionDecl>(Active->Entity)
620  << Active->InstantiationRange;
621  break;
622 
624  Diags.Report(Active->PointOfInstantiation,
625  diag::note_in_declaration_of_implicit_special_member)
626  << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
627  break;
628 
630  // FIXME: For synthesized members other than special members, produce a note.
631  auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
632  auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
633  if (CSM != CXXInvalid) {
634  Diags.Report(Active->PointOfInstantiation,
635  diag::note_member_synthesized_at)
636  << CSM << Context.getTagDeclType(MD->getParent());
637  }
638  break;
639  }
640  }
641 }
642 
645  return Optional<TemplateDeductionInfo *>(nullptr);
646 
648  Active = CodeSynthesisContexts.rbegin(),
649  ActiveEnd = CodeSynthesisContexts.rend();
650  Active != ActiveEnd;
651  ++Active)
652  {
653  switch (Active->Kind) {
655  // An instantiation of an alias template may or may not be a SFINAE
656  // context, depending on what else is on the stack.
657  if (isa<TypeAliasTemplateDecl>(Active->Entity))
658  break;
659  // Fall through.
662  // This is a template instantiation, so there is no SFINAE.
663  return None;
664 
668  // A default template argument instantiation and substitution into
669  // template parameters with arguments for prior parameters may or may
670  // not be a SFINAE context; look further up the stack.
671  break;
672 
675  // We're either substitution explicitly-specified template arguments
676  // or deduced template arguments, so SFINAE applies.
677  assert(Active->DeductionInfo && "Missing deduction info pointer");
678  return Active->DeductionInfo;
679 
682  // This happens in a context unrelated to template instantiation, so
683  // there is no SFINAE.
684  return None;
685  }
686 
687  // The inner context was transparent for SFINAE. If it occurred within a
688  // non-instantiation SFINAE context, then SFINAE applies.
689  if (Active->SavedInNonInstantiationSFINAEContext)
690  return Optional<TemplateDeductionInfo *>(nullptr);
691  }
692 
693  return None;
694 }
695 
696 /// \brief Retrieve the depth and index of a parameter pack.
697 static std::pair<unsigned, unsigned>
699  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
700  return std::make_pair(TTP->getDepth(), TTP->getIndex());
701 
702  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
703  return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
704 
705  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
706  return std::make_pair(TTP->getDepth(), TTP->getIndex());
707 }
708 
709 //===----------------------------------------------------------------------===/
710 // Template Instantiation for Types
711 //===----------------------------------------------------------------------===/
712 namespace {
713  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
714  const MultiLevelTemplateArgumentList &TemplateArgs;
715  SourceLocation Loc;
716  DeclarationName Entity;
717 
718  public:
719  typedef TreeTransform<TemplateInstantiator> inherited;
720 
721  TemplateInstantiator(Sema &SemaRef,
722  const MultiLevelTemplateArgumentList &TemplateArgs,
723  SourceLocation Loc,
724  DeclarationName Entity)
725  : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
726  Entity(Entity) { }
727 
728  /// \brief Determine whether the given type \p T has already been
729  /// transformed.
730  ///
731  /// For the purposes of template instantiation, a type has already been
732  /// transformed if it is NULL or if it is not dependent.
733  bool AlreadyTransformed(QualType T);
734 
735  /// \brief Returns the location of the entity being instantiated, if known.
736  SourceLocation getBaseLocation() { return Loc; }
737 
738  /// \brief Returns the name of the entity being instantiated, if any.
739  DeclarationName getBaseEntity() { return Entity; }
740 
741  /// \brief Sets the "base" location and entity when that
742  /// information is known based on another transformation.
743  void setBase(SourceLocation Loc, DeclarationName Entity) {
744  this->Loc = Loc;
745  this->Entity = Entity;
746  }
747 
748  bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
749  SourceRange PatternRange,
751  bool &ShouldExpand, bool &RetainExpansion,
752  Optional<unsigned> &NumExpansions) {
753  return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
754  PatternRange, Unexpanded,
755  TemplateArgs,
756  ShouldExpand,
757  RetainExpansion,
758  NumExpansions);
759  }
760 
761  void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
763  }
764 
765  TemplateArgument ForgetPartiallySubstitutedPack() {
767  if (NamedDecl *PartialPack
769  MultiLevelTemplateArgumentList &TemplateArgs
770  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
771  unsigned Depth, Index;
772  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
773  if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
774  Result = TemplateArgs(Depth, Index);
775  TemplateArgs.setArgument(Depth, Index, TemplateArgument());
776  }
777  }
778 
779  return Result;
780  }
781 
782  void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
783  if (Arg.isNull())
784  return;
785 
786  if (NamedDecl *PartialPack
788  MultiLevelTemplateArgumentList &TemplateArgs
789  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
790  unsigned Depth, Index;
791  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
792  TemplateArgs.setArgument(Depth, Index, Arg);
793  }
794  }
795 
796  /// \brief Transform the given declaration by instantiating a reference to
797  /// this declaration.
798  Decl *TransformDecl(SourceLocation Loc, Decl *D);
799 
800  void transformAttrs(Decl *Old, Decl *New) {
801  SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
802  }
803 
804  void transformedLocalDecl(Decl *Old, Decl *New) {
805  // If we've instantiated the call operator of a lambda or the call
806  // operator template of a generic lambda, update the "instantiation of"
807  // information.
808  auto *NewMD = dyn_cast<CXXMethodDecl>(New);
809  if (NewMD && isLambdaCallOperator(NewMD)) {
810  auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
811  if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
812  NewTD->setInstantiatedFromMemberTemplate(
813  OldMD->getDescribedFunctionTemplate());
814  else
817  }
818 
819  SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
820 
821  // We recreated a local declaration, but not by instantiating it. There
822  // may be pending dependent diagnostics to produce.
823  if (auto *DC = dyn_cast<DeclContext>(Old))
824  SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
825  }
826 
827  /// \brief Transform the definition of the given declaration by
828  /// instantiating it.
829  Decl *TransformDefinition(SourceLocation Loc, Decl *D);
830 
831  /// \brief Transform the first qualifier within a scope by instantiating the
832  /// declaration.
833  NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
834 
835  /// \brief Rebuild the exception declaration and register the declaration
836  /// as an instantiated local.
837  VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
839  SourceLocation StartLoc,
840  SourceLocation NameLoc,
842 
843  /// \brief Rebuild the Objective-C exception declaration and register the
844  /// declaration as an instantiated local.
845  VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
846  TypeSourceInfo *TSInfo, QualType T);
847 
848  /// \brief Check for tag mismatches when instantiating an
849  /// elaborated type.
850  QualType RebuildElaboratedType(SourceLocation KeywordLoc,
851  ElaboratedTypeKeyword Keyword,
852  NestedNameSpecifierLoc QualifierLoc,
853  QualType T);
854 
856  TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
857  SourceLocation NameLoc,
858  QualType ObjectType = QualType(),
859  NamedDecl *FirstQualifierInScope = nullptr,
860  bool AllowInjectedClassName = false);
861 
862  const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
863 
864  ExprResult TransformPredefinedExpr(PredefinedExpr *E);
865  ExprResult TransformDeclRefExpr(DeclRefExpr *E);
866  ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
867 
868  ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
870  ExprResult TransformSubstNonTypeTemplateParmPackExpr(
872 
873  /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
874  ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
875 
876  /// \brief Transform a reference to a function parameter pack.
877  ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
878  ParmVarDecl *PD);
879 
880  /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
881  /// expand a function parameter pack reference which refers to an expanded
882  /// pack.
883  ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
884 
885  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
887  // Call the base version; it will forward to our overridden version below.
888  return inherited::TransformFunctionProtoType(TLB, TL);
889  }
890 
891  template<typename Fn>
892  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
894  CXXRecordDecl *ThisContext,
895  unsigned ThisTypeQuals,
896  Fn TransformExceptionSpec);
897 
898  ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
899  int indexAdjustment,
900  Optional<unsigned> NumExpansions,
901  bool ExpectParameterPack);
902 
903  /// \brief Transforms a template type parameter type by performing
904  /// substitution of the corresponding template type argument.
905  QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
907 
908  /// \brief Transforms an already-substituted template type parameter pack
909  /// into either itself (if we aren't substituting into its pack expansion)
910  /// or the appropriate substituted argument.
911  QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
913 
914  ExprResult TransformLambdaExpr(LambdaExpr *E) {
915  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
917  }
918 
919  TemplateParameterList *TransformTemplateParameterList(
920  TemplateParameterList *OrigTPL) {
921  if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
922 
923  DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
924  TemplateDeclInstantiator DeclInstantiator(getSema(),
925  /* DeclContext *Owner */ Owner, TemplateArgs);
926  return DeclInstantiator.SubstTemplateParams(OrigTPL);
927  }
928  private:
929  ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
930  SourceLocation loc,
931  TemplateArgument arg);
932  };
933 }
934 
935 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
936  if (T.isNull())
937  return true;
938 
940  return false;
941 
942  getSema().MarkDeclarationsReferencedInType(Loc, T);
943  return true;
944 }
945 
946 static TemplateArgument
948  assert(S.ArgumentPackSubstitutionIndex >= 0);
949  assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
951  if (Arg.isPackExpansion())
952  Arg = Arg.getPackExpansionPattern();
953  return Arg;
954 }
955 
956 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
957  if (!D)
958  return nullptr;
959 
960  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
961  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
962  // If the corresponding template argument is NULL or non-existent, it's
963  // because we are performing instantiation from explicitly-specified
964  // template arguments in a function template, but there were some
965  // arguments left unspecified.
966  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
967  TTP->getPosition()))
968  return D;
969 
970  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
971 
972  if (TTP->isParameterPack()) {
973  assert(Arg.getKind() == TemplateArgument::Pack &&
974  "Missing argument pack");
975  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
976  }
977 
978  TemplateName Template = Arg.getAsTemplate();
979  assert(!Template.isNull() && Template.getAsTemplateDecl() &&
980  "Wrong kind of template template argument");
981  return Template.getAsTemplateDecl();
982  }
983 
984  // Fall through to find the instantiated declaration for this template
985  // template parameter.
986  }
987 
988  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
989 }
990 
991 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
992  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
993  if (!Inst)
994  return nullptr;
995 
996  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
997  return Inst;
998 }
999 
1000 NamedDecl *
1001 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1002  SourceLocation Loc) {
1003  // If the first part of the nested-name-specifier was a template type
1004  // parameter, instantiate that type parameter down to a tag type.
1005  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1006  const TemplateTypeParmType *TTP
1007  = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1008 
1009  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1010  // FIXME: This needs testing w/ member access expressions.
1011  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1012 
1013  if (TTP->isParameterPack()) {
1014  assert(Arg.getKind() == TemplateArgument::Pack &&
1015  "Missing argument pack");
1016 
1017  if (getSema().ArgumentPackSubstitutionIndex == -1)
1018  return nullptr;
1019 
1020  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1021  }
1022 
1023  QualType T = Arg.getAsType();
1024  if (T.isNull())
1025  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1026 
1027  if (const TagType *Tag = T->getAs<TagType>())
1028  return Tag->getDecl();
1029 
1030  // The resulting type is not a tag; complain.
1031  getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1032  return nullptr;
1033  }
1034  }
1035 
1036  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1037 }
1038 
1039 VarDecl *
1040 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1042  SourceLocation StartLoc,
1043  SourceLocation NameLoc,
1044  IdentifierInfo *Name) {
1045  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1046  StartLoc, NameLoc, Name);
1047  if (Var)
1048  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1049  return Var;
1050 }
1051 
1052 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1053  TypeSourceInfo *TSInfo,
1054  QualType T) {
1055  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1056  if (Var)
1057  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1058  return Var;
1059 }
1060 
1061 QualType
1062 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1063  ElaboratedTypeKeyword Keyword,
1064  NestedNameSpecifierLoc QualifierLoc,
1065  QualType T) {
1066  if (const TagType *TT = T->getAs<TagType>()) {
1067  TagDecl* TD = TT->getDecl();
1068 
1069  SourceLocation TagLocation = KeywordLoc;
1070 
1071  IdentifierInfo *Id = TD->getIdentifier();
1072 
1073  // TODO: should we even warn on struct/class mismatches for this? Seems
1074  // like it's likely to produce a lot of spurious errors.
1075  if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1077  if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1078  TagLocation, Id)) {
1079  SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1080  << Id
1081  << FixItHint::CreateReplacement(SourceRange(TagLocation),
1082  TD->getKindName());
1083  SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1084  }
1085  }
1086  }
1087 
1089  Keyword,
1090  QualifierLoc,
1091  T);
1092 }
1093 
1094 TemplateName TemplateInstantiator::TransformTemplateName(
1095  CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1096  QualType ObjectType, NamedDecl *FirstQualifierInScope,
1097  bool AllowInjectedClassName) {
1098  if (TemplateTemplateParmDecl *TTP
1099  = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1100  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1101  // If the corresponding template argument is NULL or non-existent, it's
1102  // because we are performing instantiation from explicitly-specified
1103  // template arguments in a function template, but there were some
1104  // arguments left unspecified.
1105  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1106  TTP->getPosition()))
1107  return Name;
1108 
1109  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1110 
1111  if (TTP->isParameterPack()) {
1112  assert(Arg.getKind() == TemplateArgument::Pack &&
1113  "Missing argument pack");
1114 
1115  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1116  // We have the template argument pack to substitute, but we're not
1117  // actually expanding the enclosing pack expansion yet. So, just
1118  // keep the entire argument pack.
1119  return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1120  }
1121 
1122  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1123  }
1124 
1125  TemplateName Template = Arg.getAsTemplate();
1126  assert(!Template.isNull() && "Null template template argument");
1127 
1128  // We don't ever want to substitute for a qualified template name, since
1129  // the qualifier is handled separately. So, look through the qualified
1130  // template name to its underlying declaration.
1131  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1132  Template = TemplateName(QTN->getTemplateDecl());
1133 
1134  Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1135  return Template;
1136  }
1137  }
1138 
1141  if (getSema().ArgumentPackSubstitutionIndex == -1)
1142  return Name;
1143 
1144  TemplateArgument Arg = SubstPack->getArgumentPack();
1145  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1146  return Arg.getAsTemplate();
1147  }
1148 
1149  return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1150  FirstQualifierInScope,
1151  AllowInjectedClassName);
1152 }
1153 
1154 ExprResult
1155 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1156  if (!E->isTypeDependent())
1157  return E;
1158 
1159  return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1160 }
1161 
1162 ExprResult
1163 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1164  NonTypeTemplateParmDecl *NTTP) {
1165  // If the corresponding template argument is NULL or non-existent, it's
1166  // because we are performing instantiation from explicitly-specified
1167  // template arguments in a function template, but there were some
1168  // arguments left unspecified.
1169  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1170  NTTP->getPosition()))
1171  return E;
1172 
1173  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1174 
1175  if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1176  // We're performing a partial substitution, so the substituted argument
1177  // could be dependent. As a result we can't create a SubstNonType*Expr
1178  // node now, since that represents a fully-substituted argument.
1179  // FIXME: We should have some AST representation for this.
1180  if (Arg.getKind() == TemplateArgument::Pack) {
1181  // FIXME: This won't work for alias templates.
1182  assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1183  "unexpected pack arguments in partial substitution");
1184  Arg = Arg.pack_begin()->getPackExpansionPattern();
1185  }
1186  assert(Arg.getKind() == TemplateArgument::Expression &&
1187  "unexpected nontype template argument kind in partial substitution");
1188  return Arg.getAsExpr();
1189  }
1190 
1191  if (NTTP->isParameterPack()) {
1192  assert(Arg.getKind() == TemplateArgument::Pack &&
1193  "Missing argument pack");
1194 
1195  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1196  // We have an argument pack, but we can't select a particular argument
1197  // out of it yet. Therefore, we'll build an expression to hold on to that
1198  // argument pack.
1199  QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1200  E->getLocation(),
1201  NTTP->getDeclName());
1202  if (TargetType.isNull())
1203  return ExprError();
1204 
1205  return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1206  NTTP,
1207  E->getLocation(),
1208  Arg);
1209  }
1210 
1211  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1212  }
1213 
1214  return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1215 }
1216 
1217 const LoopHintAttr *
1218 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1219  Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1220 
1221  if (TransformedExpr == LH->getValue())
1222  return LH;
1223 
1224  // Generate error if there is a problem with the value.
1225  if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1226  return LH;
1227 
1228  // Create new LoopHintValueAttr with integral expression in place of the
1229  // non-type template parameter.
1230  return LoopHintAttr::CreateImplicit(
1231  getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1232  LH->getState(), TransformedExpr, LH->getRange());
1233 }
1234 
1235 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1237  SourceLocation loc,
1238  TemplateArgument arg) {
1239  ExprResult result;
1240  QualType type;
1241 
1242  // The template argument itself might be an expression, in which
1243  // case we just return that expression.
1244  if (arg.getKind() == TemplateArgument::Expression) {
1245  Expr *argExpr = arg.getAsExpr();
1246  result = argExpr;
1247  type = argExpr->getType();
1248 
1249  } else if (arg.getKind() == TemplateArgument::Declaration ||
1251  ValueDecl *VD;
1252  if (arg.getKind() == TemplateArgument::Declaration) {
1253  VD = cast<ValueDecl>(arg.getAsDecl());
1254 
1255  // Find the instantiation of the template argument. This is
1256  // required for nested templates.
1257  VD = cast_or_null<ValueDecl>(
1258  getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1259  if (!VD)
1260  return ExprError();
1261  } else {
1262  // Propagate NULL template argument.
1263  VD = nullptr;
1264  }
1265 
1266  // Derive the type we want the substituted decl to have. This had
1267  // better be non-dependent, or these checks will have serious problems.
1268  if (parm->isExpandedParameterPack()) {
1269  type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1270  } else if (parm->isParameterPack() &&
1271  isa<PackExpansionType>(parm->getType())) {
1272  type = SemaRef.SubstType(
1273  cast<PackExpansionType>(parm->getType())->getPattern(),
1274  TemplateArgs, loc, parm->getDeclName());
1275  } else {
1276  type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1277  TemplateArgs, loc, parm->getDeclName());
1278  }
1279  assert(!type.isNull() && "type substitution failed for param type");
1280  assert(!type->isDependentType() && "param type still dependent");
1281  result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1282 
1283  if (!result.isInvalid()) type = result.get()->getType();
1284  } else {
1285  result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1286 
1287  // Note that this type can be different from the type of 'result',
1288  // e.g. if it's an enum type.
1289  type = arg.getIntegralType();
1290  }
1291  if (result.isInvalid()) return ExprError();
1292 
1293  Expr *resultExpr = result.get();
1294  return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1295  type, resultExpr->getValueKind(), loc, parm, resultExpr);
1296 }
1297 
1298 ExprResult
1299 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1301  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1302  // We aren't expanding the parameter pack, so just return ourselves.
1303  return E;
1304  }
1305 
1306  TemplateArgument Arg = E->getArgumentPack();
1307  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1308  return transformNonTypeTemplateParmRef(E->getParameterPack(),
1310  Arg);
1311 }
1312 
1313 ExprResult
1314 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1315  SourceLocation Loc) {
1316  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1317  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1318 }
1319 
1320 ExprResult
1321 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1322  if (getSema().ArgumentPackSubstitutionIndex != -1) {
1323  // We can expand this parameter pack now.
1325  ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1326  if (!VD)
1327  return ExprError();
1328  return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1329  }
1330 
1331  QualType T = TransformType(E->getType());
1332  if (T.isNull())
1333  return ExprError();
1334 
1335  // Transform each of the parameter expansions into the corresponding
1336  // parameters in the instantiation of the function decl.
1338  Parms.reserve(E->getNumExpansions());
1339  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1340  I != End; ++I) {
1341  ParmVarDecl *D =
1342  cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1343  if (!D)
1344  return ExprError();
1345  Parms.push_back(D);
1346  }
1347 
1348  return FunctionParmPackExpr::Create(getSema().Context, T,
1349  E->getParameterPack(),
1350  E->getParameterPackLocation(), Parms);
1351 }
1352 
1353 ExprResult
1354 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1355  ParmVarDecl *PD) {
1356  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1357  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1358  = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1359  assert(Found && "no instantiation for parameter pack");
1360 
1361  Decl *TransformedDecl;
1362  if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1363  // If this is a reference to a function parameter pack which we can
1364  // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1365  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1366  QualType T = TransformType(E->getType());
1367  if (T.isNull())
1368  return ExprError();
1369  return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1370  E->getExprLoc(), *Pack);
1371  }
1372 
1373  TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1374  } else {
1375  TransformedDecl = Found->get<Decl*>();
1376  }
1377 
1378  // We have either an unexpanded pack or a specific expansion.
1379  return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1380  E->getExprLoc());
1381 }
1382 
1383 ExprResult
1384 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1385  NamedDecl *D = E->getDecl();
1386 
1387  // Handle references to non-type template parameters and non-type template
1388  // parameter packs.
1389  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1390  if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1391  return TransformTemplateParmRefExpr(E, NTTP);
1392 
1393  // We have a non-type template parameter that isn't fully substituted;
1394  // FindInstantiatedDecl will find it in the local instantiation scope.
1395  }
1396 
1397  // Handle references to function parameter packs.
1398  if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1399  if (PD->isParameterPack())
1400  return TransformFunctionParmPackRefExpr(E, PD);
1401 
1403 }
1404 
1405 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1406  CXXDefaultArgExpr *E) {
1407  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1408  getDescribedFunctionTemplate() &&
1409  "Default arg expressions are never formed in dependent cases.");
1410  return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1411  cast<FunctionDecl>(E->getParam()->getDeclContext()),
1412  E->getParam());
1413 }
1414 
1415 template<typename Fn>
1416 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1418  CXXRecordDecl *ThisContext,
1419  unsigned ThisTypeQuals,
1420  Fn TransformExceptionSpec) {
1421  // We need a local instantiation scope for this function prototype.
1422  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1423  return inherited::TransformFunctionProtoType(
1424  TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1425 }
1426 
1427 ParmVarDecl *
1428 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1429  int indexAdjustment,
1430  Optional<unsigned> NumExpansions,
1431  bool ExpectParameterPack) {
1432  return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1433  NumExpansions, ExpectParameterPack);
1434 }
1435 
1436 QualType
1437 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1439  const TemplateTypeParmType *T = TL.getTypePtr();
1440  if (T->getDepth() < TemplateArgs.getNumLevels()) {
1441  // Replace the template type parameter with its corresponding
1442  // template argument.
1443 
1444  // If the corresponding template argument is NULL or doesn't exist, it's
1445  // because we are performing instantiation from explicitly-specified
1446  // template arguments in a function template class, but there were some
1447  // arguments left unspecified.
1448  if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1450  = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1451  NewTL.setNameLoc(TL.getNameLoc());
1452  return TL.getType();
1453  }
1454 
1455  TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1456 
1457  if (T->isParameterPack()) {
1458  assert(Arg.getKind() == TemplateArgument::Pack &&
1459  "Missing argument pack");
1460 
1461  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1462  // We have the template argument pack, but we're not expanding the
1463  // enclosing pack expansion yet. Just save the template argument
1464  // pack for later substitution.
1465  QualType Result
1466  = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1469  NewTL.setNameLoc(TL.getNameLoc());
1470  return Result;
1471  }
1472 
1473  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1474  }
1475 
1476  assert(Arg.getKind() == TemplateArgument::Type &&
1477  "Template argument kind mismatch");
1478 
1479  QualType Replacement = Arg.getAsType();
1480 
1481  // TODO: only do this uniquing once, at the start of instantiation.
1482  QualType Result
1483  = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1486  NewTL.setNameLoc(TL.getNameLoc());
1487  return Result;
1488  }
1489 
1490  // The template type parameter comes from an inner template (e.g.,
1491  // the template parameter list of a member template inside the
1492  // template we are instantiating). Create a new template type
1493  // parameter with the template "level" reduced by one.
1494  TemplateTypeParmDecl *NewTTPDecl = nullptr;
1495  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1496  NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1497  TransformDecl(TL.getNameLoc(), OldTTPDecl));
1498 
1499  QualType Result = getSema().Context.getTemplateTypeParmType(
1500  T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1501  T->isParameterPack(), NewTTPDecl);
1503  NewTL.setNameLoc(TL.getNameLoc());
1504  return Result;
1505 }
1506 
1507 QualType
1508 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1509  TypeLocBuilder &TLB,
1511  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1512  // We aren't expanding the parameter pack, so just return ourselves.
1515  NewTL.setNameLoc(TL.getNameLoc());
1516  return TL.getType();
1517  }
1518 
1520  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1521  QualType Result = Arg.getAsType();
1522 
1523  Result = getSema().Context.getSubstTemplateTypeParmType(
1525  Result);
1528  NewTL.setNameLoc(TL.getNameLoc());
1529  return Result;
1530 }
1531 
1532 /// \brief Perform substitution on the type T with a given set of template
1533 /// arguments.
1534 ///
1535 /// This routine substitutes the given template arguments into the
1536 /// type T and produces the instantiated type.
1537 ///
1538 /// \param T the type into which the template arguments will be
1539 /// substituted. If this type is not dependent, it will be returned
1540 /// immediately.
1541 ///
1542 /// \param Args the template arguments that will be
1543 /// substituted for the top-level template parameters within T.
1544 ///
1545 /// \param Loc the location in the source code where this substitution
1546 /// is being performed. It will typically be the location of the
1547 /// declarator (if we're instantiating the type of some declaration)
1548 /// or the location of the type in the source code (if, e.g., we're
1549 /// instantiating the type of a cast expression).
1550 ///
1551 /// \param Entity the name of the entity associated with a declaration
1552 /// being instantiated (if any). May be empty to indicate that there
1553 /// is no such entity (if, e.g., this is a type that occurs as part of
1554 /// a cast expression) or that the entity has no name (e.g., an
1555 /// unnamed function parameter).
1556 ///
1557 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1558 /// acceptable as the top level type of the result.
1559 ///
1560 /// \returns If the instantiation succeeds, the instantiated
1561 /// type. Otherwise, produces diagnostics and returns a NULL type.
1563  const MultiLevelTemplateArgumentList &Args,
1564  SourceLocation Loc,
1565  DeclarationName Entity,
1566  bool AllowDeducedTST) {
1567  assert(!CodeSynthesisContexts.empty() &&
1568  "Cannot perform an instantiation without some context on the "
1569  "instantiation stack");
1570 
1571  if (!T->getType()->isInstantiationDependentType() &&
1573  return T;
1574 
1575  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1576  return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1577  : Instantiator.TransformType(T);
1578 }
1579 
1581  const MultiLevelTemplateArgumentList &Args,
1582  SourceLocation Loc,
1583  DeclarationName Entity) {
1584  assert(!CodeSynthesisContexts.empty() &&
1585  "Cannot perform an instantiation without some context on the "
1586  "instantiation stack");
1587 
1588  if (TL.getType().isNull())
1589  return nullptr;
1590 
1591  if (!TL.getType()->isInstantiationDependentType() &&
1592  !TL.getType()->isVariablyModifiedType()) {
1593  // FIXME: Make a copy of the TypeLoc data here, so that we can
1594  // return a new TypeSourceInfo. Inefficient!
1595  TypeLocBuilder TLB;
1596  TLB.pushFullCopy(TL);
1597  return TLB.getTypeSourceInfo(Context, TL.getType());
1598  }
1599 
1600  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1601  TypeLocBuilder TLB;
1602  TLB.reserve(TL.getFullDataSize());
1603  QualType Result = Instantiator.TransformType(TLB, TL);
1604  if (Result.isNull())
1605  return nullptr;
1606 
1607  return TLB.getTypeSourceInfo(Context, Result);
1608 }
1609 
1610 /// Deprecated form of the above.
1612  const MultiLevelTemplateArgumentList &TemplateArgs,
1613  SourceLocation Loc, DeclarationName Entity) {
1614  assert(!CodeSynthesisContexts.empty() &&
1615  "Cannot perform an instantiation without some context on the "
1616  "instantiation stack");
1617 
1618  // If T is not a dependent type or a variably-modified type, there
1619  // is nothing to do.
1621  return T;
1622 
1623  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1624  return Instantiator.TransformType(T);
1625 }
1626 
1628  if (T->getType()->isInstantiationDependentType() ||
1630  return true;
1631 
1632  TypeLoc TL = T->getTypeLoc().IgnoreParens();
1633  if (!TL.getAs<FunctionProtoTypeLoc>())
1634  return false;
1635 
1637  for (ParmVarDecl *P : FP.getParams()) {
1638  // This must be synthesized from a typedef.
1639  if (!P) continue;
1640 
1641  // If there are any parameters, a new TypeSourceInfo that refers to the
1642  // instantiated parameters must be built.
1643  return true;
1644  }
1645 
1646  return false;
1647 }
1648 
1649 /// A form of SubstType intended specifically for instantiating the
1650 /// type of a FunctionDecl. Its purpose is solely to force the
1651 /// instantiation of default-argument expressions and to avoid
1652 /// instantiating an exception-specification.
1654  const MultiLevelTemplateArgumentList &Args,
1655  SourceLocation Loc,
1656  DeclarationName Entity,
1657  CXXRecordDecl *ThisContext,
1658  unsigned ThisTypeQuals) {
1659  assert(!CodeSynthesisContexts.empty() &&
1660  "Cannot perform an instantiation without some context on the "
1661  "instantiation stack");
1662 
1664  return T;
1665 
1666  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1667 
1668  TypeLocBuilder TLB;
1669 
1670  TypeLoc TL = T->getTypeLoc();
1671  TLB.reserve(TL.getFullDataSize());
1672 
1673  QualType Result;
1674 
1675  if (FunctionProtoTypeLoc Proto =
1677  // Instantiate the type, other than its exception specification. The
1678  // exception specification is instantiated in InitFunctionInstantiation
1679  // once we've built the FunctionDecl.
1680  // FIXME: Set the exception specification to EST_Uninstantiated here,
1681  // instead of rebuilding the function type again later.
1682  Result = Instantiator.TransformFunctionProtoType(
1683  TLB, Proto, ThisContext, ThisTypeQuals,
1685  bool &Changed) { return false; });
1686  } else {
1687  Result = Instantiator.TransformType(TLB, TL);
1688  }
1689  if (Result.isNull())
1690  return nullptr;
1691 
1692  return TLB.getTypeSourceInfo(Context, Result);
1693 }
1694 
1697  SmallVectorImpl<QualType> &ExceptionStorage,
1698  const MultiLevelTemplateArgumentList &Args) {
1699  assert(ESI.Type != EST_Uninstantiated);
1700 
1701  bool Changed = false;
1702  TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1703  return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1704  Changed);
1705 }
1706 
1708  const MultiLevelTemplateArgumentList &Args) {
1710  Proto->getExtProtoInfo().ExceptionSpec;
1711 
1712  SmallVector<QualType, 4> ExceptionStorage;
1714  ESI, ExceptionStorage, Args))
1715  // On error, recover by dropping the exception specification.
1716  ESI.Type = EST_None;
1717 
1718  UpdateExceptionSpec(New, ESI);
1719 }
1720 
1722  const MultiLevelTemplateArgumentList &TemplateArgs,
1723  int indexAdjustment,
1724  Optional<unsigned> NumExpansions,
1725  bool ExpectParameterPack) {
1726  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1727  TypeSourceInfo *NewDI = nullptr;
1728 
1729  TypeLoc OldTL = OldDI->getTypeLoc();
1730  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1731 
1732  // We have a function parameter pack. Substitute into the pattern of the
1733  // expansion.
1734  NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1735  OldParm->getLocation(), OldParm->getDeclName());
1736  if (!NewDI)
1737  return nullptr;
1738 
1739  if (NewDI->getType()->containsUnexpandedParameterPack()) {
1740  // We still have unexpanded parameter packs, which means that
1741  // our function parameter is still a function parameter pack.
1742  // Therefore, make its type a pack expansion type.
1743  NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1744  NumExpansions);
1745  } else if (ExpectParameterPack) {
1746  // We expected to get a parameter pack but didn't (because the type
1747  // itself is not a pack expansion type), so complain. This can occur when
1748  // the substitution goes through an alias template that "loses" the
1749  // pack expansion.
1750  Diag(OldParm->getLocation(),
1751  diag::err_function_parameter_pack_without_parameter_packs)
1752  << NewDI->getType();
1753  return nullptr;
1754  }
1755  } else {
1756  NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1757  OldParm->getDeclName());
1758  }
1759 
1760  if (!NewDI)
1761  return nullptr;
1762 
1763  if (NewDI->getType()->isVoidType()) {
1764  Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1765  return nullptr;
1766  }
1767 
1769  OldParm->getInnerLocStart(),
1770  OldParm->getLocation(),
1771  OldParm->getIdentifier(),
1772  NewDI->getType(), NewDI,
1773  OldParm->getStorageClass());
1774  if (!NewParm)
1775  return nullptr;
1776 
1777  // Mark the (new) default argument as uninstantiated (if any).
1778  if (OldParm->hasUninstantiatedDefaultArg()) {
1779  Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1780  NewParm->setUninstantiatedDefaultArg(Arg);
1781  } else if (OldParm->hasUnparsedDefaultArg()) {
1782  NewParm->setUnparsedDefaultArg();
1783  UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1784  } else if (Expr *Arg = OldParm->getDefaultArg()) {
1785  FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1786  if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1787  // Instantiate default arguments for methods of local classes (DR1484)
1788  // and non-defining declarations.
1789  Sema::ContextRAII SavedContext(*this, OwningFunc);
1790  LocalInstantiationScope Local(*this, true);
1791  ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1792  if (NewArg.isUsable()) {
1793  // It would be nice if we still had this.
1794  SourceLocation EqualLoc = NewArg.get()->getLocStart();
1795  SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1796  }
1797  } else {
1798  // FIXME: if we non-lazily instantiated non-dependent default args for
1799  // non-dependent parameter types we could remove a bunch of duplicate
1800  // conversion warnings for such arguments.
1801  NewParm->setUninstantiatedDefaultArg(Arg);
1802  }
1803  }
1804 
1806 
1807  if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1808  // Add the new parameter to the instantiated parameter pack.
1810  } else {
1811  // Introduce an Old -> New mapping
1812  CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1813  }
1814 
1815  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1816  // can be anything, is this right ?
1817  NewParm->setDeclContext(CurContext);
1818 
1819  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1820  OldParm->getFunctionScopeIndex() + indexAdjustment);
1821 
1822  InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1823 
1824  return NewParm;
1825 }
1826 
1827 /// \brief Substitute the given template arguments into the given set of
1828 /// parameters, producing the set of parameter types that would be generated
1829 /// from such a substitution.
1832  const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1833  const MultiLevelTemplateArgumentList &TemplateArgs,
1834  SmallVectorImpl<QualType> &ParamTypes,
1835  SmallVectorImpl<ParmVarDecl *> *OutParams,
1836  ExtParameterInfoBuilder &ParamInfos) {
1837  assert(!CodeSynthesisContexts.empty() &&
1838  "Cannot perform an instantiation without some context on the "
1839  "instantiation stack");
1840 
1841  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1842  DeclarationName());
1843  return Instantiator.TransformFunctionTypeParams(
1844  Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1845 }
1846 
1847 /// \brief Perform substitution on the base class specifiers of the
1848 /// given class template specialization.
1849 ///
1850 /// Produces a diagnostic and returns true on error, returns false and
1851 /// attaches the instantiated base classes to the class template
1852 /// specialization if successful.
1853 bool
1855  CXXRecordDecl *Pattern,
1856  const MultiLevelTemplateArgumentList &TemplateArgs) {
1857  bool Invalid = false;
1858  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1859  for (const auto &Base : Pattern->bases()) {
1860  if (!Base.getType()->isDependentType()) {
1861  if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1862  if (RD->isInvalidDecl())
1863  Instantiation->setInvalidDecl();
1864  }
1865  InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1866  continue;
1867  }
1868 
1869  SourceLocation EllipsisLoc;
1870  TypeSourceInfo *BaseTypeLoc;
1871  if (Base.isPackExpansion()) {
1872  // This is a pack expansion. See whether we should expand it now, or
1873  // wait until later.
1875  collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1876  Unexpanded);
1877  bool ShouldExpand = false;
1878  bool RetainExpansion = false;
1879  Optional<unsigned> NumExpansions;
1880  if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1881  Base.getSourceRange(),
1882  Unexpanded,
1883  TemplateArgs, ShouldExpand,
1884  RetainExpansion,
1885  NumExpansions)) {
1886  Invalid = true;
1887  continue;
1888  }
1889 
1890  // If we should expand this pack expansion now, do so.
1891  if (ShouldExpand) {
1892  for (unsigned I = 0; I != *NumExpansions; ++I) {
1893  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1894 
1895  TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1896  TemplateArgs,
1897  Base.getSourceRange().getBegin(),
1898  DeclarationName());
1899  if (!BaseTypeLoc) {
1900  Invalid = true;
1901  continue;
1902  }
1903 
1904  if (CXXBaseSpecifier *InstantiatedBase
1905  = CheckBaseSpecifier(Instantiation,
1906  Base.getSourceRange(),
1907  Base.isVirtual(),
1908  Base.getAccessSpecifierAsWritten(),
1909  BaseTypeLoc,
1910  SourceLocation()))
1911  InstantiatedBases.push_back(InstantiatedBase);
1912  else
1913  Invalid = true;
1914  }
1915 
1916  continue;
1917  }
1918 
1919  // The resulting base specifier will (still) be a pack expansion.
1920  EllipsisLoc = Base.getEllipsisLoc();
1921  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1922  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1923  TemplateArgs,
1924  Base.getSourceRange().getBegin(),
1925  DeclarationName());
1926  } else {
1927  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1928  TemplateArgs,
1929  Base.getSourceRange().getBegin(),
1930  DeclarationName());
1931  }
1932 
1933  if (!BaseTypeLoc) {
1934  Invalid = true;
1935  continue;
1936  }
1937 
1938  if (CXXBaseSpecifier *InstantiatedBase
1939  = CheckBaseSpecifier(Instantiation,
1940  Base.getSourceRange(),
1941  Base.isVirtual(),
1942  Base.getAccessSpecifierAsWritten(),
1943  BaseTypeLoc,
1944  EllipsisLoc))
1945  InstantiatedBases.push_back(InstantiatedBase);
1946  else
1947  Invalid = true;
1948  }
1949 
1950  if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1951  Invalid = true;
1952 
1953  return Invalid;
1954 }
1955 
1956 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1957 namespace clang {
1958  namespace sema {
1960  const MultiLevelTemplateArgumentList &TemplateArgs);
1962  const Attr *At, ASTContext &C, Sema &S,
1963  const MultiLevelTemplateArgumentList &TemplateArgs);
1964  }
1965 }
1966 
1967 /// \brief Instantiate the definition of a class from a given pattern.
1968 ///
1969 /// \param PointOfInstantiation The point of instantiation within the
1970 /// source code.
1971 ///
1972 /// \param Instantiation is the declaration whose definition is being
1973 /// instantiated. This will be either a class template specialization
1974 /// or a member class of a class template specialization.
1975 ///
1976 /// \param Pattern is the pattern from which the instantiation
1977 /// occurs. This will be either the declaration of a class template or
1978 /// the declaration of a member class of a class template.
1979 ///
1980 /// \param TemplateArgs The template arguments to be substituted into
1981 /// the pattern.
1982 ///
1983 /// \param TSK the kind of implicit or explicit instantiation to perform.
1984 ///
1985 /// \param Complain whether to complain if the class cannot be instantiated due
1986 /// to the lack of a definition.
1987 ///
1988 /// \returns true if an error occurred, false otherwise.
1989 bool
1991  CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1992  const MultiLevelTemplateArgumentList &TemplateArgs,
1994  bool Complain) {
1995  CXXRecordDecl *PatternDef
1996  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1997  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
1998  Instantiation->getInstantiatedFromMemberClass(),
1999  Pattern, PatternDef, TSK, Complain))
2000  return true;
2001  Pattern = PatternDef;
2002 
2003  // \brief Record the point of instantiation.
2004  if (MemberSpecializationInfo *MSInfo
2005  = Instantiation->getMemberSpecializationInfo()) {
2006  MSInfo->setTemplateSpecializationKind(TSK);
2007  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2008  } else if (ClassTemplateSpecializationDecl *Spec
2009  = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2010  Spec->setTemplateSpecializationKind(TSK);
2011  Spec->setPointOfInstantiation(PointOfInstantiation);
2012  }
2013 
2014  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2015  if (Inst.isInvalid())
2016  return true;
2017  assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2018  PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2019  "instantiating class definition");
2020 
2021  // Enter the scope of this instantiation. We don't use
2022  // PushDeclContext because we don't have a scope.
2023  ContextRAII SavedContext(*this, Instantiation);
2026 
2027  // If this is an instantiation of a local class, merge this local
2028  // instantiation scope with the enclosing scope. Otherwise, every
2029  // instantiation of a class has its own local instantiation scope.
2030  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2031  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2032 
2033  // All dllexported classes created during instantiation should be fully
2034  // emitted after instantiation completes. We may not be ready to emit any
2035  // delayed classes already on the stack, so save them away and put them back
2036  // later.
2037  decltype(DelayedDllExportClasses) ExportedClasses;
2038  std::swap(ExportedClasses, DelayedDllExportClasses);
2039 
2040  // Pull attributes from the pattern onto the instantiation.
2041  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2042 
2043  // Start the definition of this instantiation.
2044  Instantiation->startDefinition();
2045 
2046  // The instantiation is visible here, even if it was first declared in an
2047  // unimported module.
2048  Instantiation->setVisibleDespiteOwningModule();
2049 
2050  // FIXME: This loses the as-written tag kind for an explicit instantiation.
2051  Instantiation->setTagKind(Pattern->getTagKind());
2052 
2053  // Do substitution on the base class specifiers.
2054  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2055  Instantiation->setInvalidDecl();
2056 
2057  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2058  SmallVector<Decl*, 4> Fields;
2059  // Delay instantiation of late parsed attributes.
2060  LateInstantiatedAttrVec LateAttrs;
2061  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2062 
2063  for (auto *Member : Pattern->decls()) {
2064  // Don't instantiate members not belonging in this semantic context.
2065  // e.g. for:
2066  // @code
2067  // template <int i> class A {
2068  // class B *g;
2069  // };
2070  // @endcode
2071  // 'class B' has the template as lexical context but semantically it is
2072  // introduced in namespace scope.
2073  if (Member->getDeclContext() != Pattern)
2074  continue;
2075 
2076  if (Member->isInvalidDecl()) {
2077  Instantiation->setInvalidDecl();
2078  continue;
2079  }
2080 
2081  Decl *NewMember = Instantiator.Visit(Member);
2082  if (NewMember) {
2083  if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2084  Fields.push_back(Field);
2085  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2086  // C++11 [temp.inst]p1: The implicit instantiation of a class template
2087  // specialization causes the implicit instantiation of the definitions
2088  // of unscoped member enumerations.
2089  // Record a point of instantiation for this implicit instantiation.
2090  if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2091  Enum->isCompleteDefinition()) {
2092  MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2093  assert(MSInfo && "no spec info for member enum specialization");
2095  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2096  }
2097  } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2098  if (SA->isFailed()) {
2099  // A static_assert failed. Bail out; instantiating this
2100  // class is probably not meaningful.
2101  Instantiation->setInvalidDecl();
2102  break;
2103  }
2104  }
2105 
2106  if (NewMember->isInvalidDecl())
2107  Instantiation->setInvalidDecl();
2108  } else {
2109  // FIXME: Eventually, a NULL return will mean that one of the
2110  // instantiations was a semantic disaster, and we'll want to mark the
2111  // declaration invalid.
2112  // For now, we expect to skip some members that we can't yet handle.
2113  }
2114  }
2115 
2116  // Finish checking fields.
2117  ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2118  SourceLocation(), SourceLocation(), nullptr);
2119  CheckCompletedCXXClass(Instantiation);
2120 
2121  // Default arguments are parsed, if not instantiated. We can go instantiate
2122  // default arg exprs for default constructors if necessary now.
2123  ActOnFinishCXXNonNestedClass(Instantiation);
2124 
2125  // Put back the delayed exported classes that we moved out of the way.
2126  std::swap(ExportedClasses, DelayedDllExportClasses);
2127 
2128  // Instantiate late parsed attributes, and attach them to their decls.
2129  // See Sema::InstantiateAttrs
2130  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2131  E = LateAttrs.end(); I != E; ++I) {
2132  assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2133  CurrentInstantiationScope = I->Scope;
2134 
2135  // Allow 'this' within late-parsed attributes.
2136  NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2137  CXXRecordDecl *ThisContext =
2138  dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2139  CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2140  ND && ND->isCXXInstanceMember());
2141 
2142  Attr *NewAttr =
2143  instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2144  I->NewDecl->addAttr(NewAttr);
2146  Instantiator.getStartingScope());
2147  }
2148  Instantiator.disableLateAttributeInstantiation();
2149  LateAttrs.clear();
2150 
2151  ActOnFinishDelayedMemberInitializers(Instantiation);
2152 
2153  // FIXME: We should do something similar for explicit instantiations so they
2154  // end up in the right module.
2155  if (TSK == TSK_ImplicitInstantiation) {
2156  Instantiation->setLocation(Pattern->getLocation());
2157  Instantiation->setLocStart(Pattern->getInnerLocStart());
2158  Instantiation->setBraceRange(Pattern->getBraceRange());
2159  }
2160 
2161  if (!Instantiation->isInvalidDecl()) {
2162  // Perform any dependent diagnostics from the pattern.
2163  PerformDependentDiagnostics(Pattern, TemplateArgs);
2164 
2165  // Instantiate any out-of-line class template partial
2166  // specializations now.
2168  P = Instantiator.delayed_partial_spec_begin(),
2169  PEnd = Instantiator.delayed_partial_spec_end();
2170  P != PEnd; ++P) {
2172  P->first, P->second)) {
2173  Instantiation->setInvalidDecl();
2174  break;
2175  }
2176  }
2177 
2178  // Instantiate any out-of-line variable template partial
2179  // specializations now.
2181  P = Instantiator.delayed_var_partial_spec_begin(),
2182  PEnd = Instantiator.delayed_var_partial_spec_end();
2183  P != PEnd; ++P) {
2185  P->first, P->second)) {
2186  Instantiation->setInvalidDecl();
2187  break;
2188  }
2189  }
2190  }
2191 
2192  // Exit the scope of this instantiation.
2193  SavedContext.pop();
2194 
2195  if (!Instantiation->isInvalidDecl()) {
2196  Consumer.HandleTagDeclDefinition(Instantiation);
2197 
2198  // Always emit the vtable for an explicit instantiation definition
2199  // of a polymorphic class template specialization.
2201  MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2202  }
2203 
2204  return Instantiation->isInvalidDecl();
2205 }
2206 
2207 /// \brief Instantiate the definition of an enum from a given pattern.
2208 ///
2209 /// \param PointOfInstantiation The point of instantiation within the
2210 /// source code.
2211 /// \param Instantiation is the declaration whose definition is being
2212 /// instantiated. This will be a member enumeration of a class
2213 /// temploid specialization, or a local enumeration within a
2214 /// function temploid specialization.
2215 /// \param Pattern The templated declaration from which the instantiation
2216 /// occurs.
2217 /// \param TemplateArgs The template arguments to be substituted into
2218 /// the pattern.
2219 /// \param TSK The kind of implicit or explicit instantiation to perform.
2220 ///
2221 /// \return \c true if an error occurred, \c false otherwise.
2222 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2223  EnumDecl *Instantiation, EnumDecl *Pattern,
2224  const MultiLevelTemplateArgumentList &TemplateArgs,
2226  EnumDecl *PatternDef = Pattern->getDefinition();
2227  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2228  Instantiation->getInstantiatedFromMemberEnum(),
2229  Pattern, PatternDef, TSK,/*Complain*/true))
2230  return true;
2231  Pattern = PatternDef;
2232 
2233  // Record the point of instantiation.
2234  if (MemberSpecializationInfo *MSInfo
2235  = Instantiation->getMemberSpecializationInfo()) {
2236  MSInfo->setTemplateSpecializationKind(TSK);
2237  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2238  }
2239 
2240  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2241  if (Inst.isInvalid())
2242  return true;
2243  if (Inst.isAlreadyInstantiating())
2244  return false;
2245  PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2246  "instantiating enum definition");
2247 
2248  // The instantiation is visible here, even if it was first declared in an
2249  // unimported module.
2250  Instantiation->setVisibleDespiteOwningModule();
2251 
2252  // Enter the scope of this instantiation. We don't use
2253  // PushDeclContext because we don't have a scope.
2254  ContextRAII SavedContext(*this, Instantiation);
2257 
2258  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2259 
2260  // Pull attributes from the pattern onto the instantiation.
2261  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2262 
2263  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2264  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2265 
2266  // Exit the scope of this instantiation.
2267  SavedContext.pop();
2268 
2269  return Instantiation->isInvalidDecl();
2270 }
2271 
2272 
2273 /// \brief Instantiate the definition of a field from the given pattern.
2274 ///
2275 /// \param PointOfInstantiation The point of instantiation within the
2276 /// source code.
2277 /// \param Instantiation is the declaration whose definition is being
2278 /// instantiated. This will be a class of a class temploid
2279 /// specialization, or a local enumeration within a function temploid
2280 /// specialization.
2281 /// \param Pattern The templated declaration from which the instantiation
2282 /// occurs.
2283 /// \param TemplateArgs The template arguments to be substituted into
2284 /// the pattern.
2285 ///
2286 /// \return \c true if an error occurred, \c false otherwise.
2288  SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2289  FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2290  // If there is no initializer, we don't need to do anything.
2291  if (!Pattern->hasInClassInitializer())
2292  return false;
2293 
2294  assert(Instantiation->getInClassInitStyle() ==
2295  Pattern->getInClassInitStyle() &&
2296  "pattern and instantiation disagree about init style");
2297 
2298  // Error out if we haven't parsed the initializer of the pattern yet because
2299  // we are waiting for the closing brace of the outer class.
2300  Expr *OldInit = Pattern->getInClassInitializer();
2301  if (!OldInit) {
2302  RecordDecl *PatternRD = Pattern->getParent();
2303  RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2304  Diag(PointOfInstantiation,
2305  diag::err_in_class_initializer_not_yet_parsed)
2306  << OutermostClass << Pattern;
2307  Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
2308  Instantiation->setInvalidDecl();
2309  return true;
2310  }
2311 
2312  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2313  if (Inst.isInvalid())
2314  return true;
2315  if (Inst.isAlreadyInstantiating()) {
2316  // Error out if we hit an instantiation cycle for this initializer.
2317  Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2318  << Instantiation;
2319  return true;
2320  }
2321  PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2322  "instantiating default member init");
2323 
2324  // Enter the scope of this instantiation. We don't use PushDeclContext because
2325  // we don't have a scope.
2326  ContextRAII SavedContext(*this, Instantiation->getParent());
2329 
2330  LocalInstantiationScope Scope(*this, true);
2331 
2332  // Instantiate the initializer.
2334  CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2335 
2336  ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2337  /*CXXDirectInit=*/false);
2338  Expr *Init = NewInit.get();
2339  assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2341  Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2342 
2343  if (auto *L = getASTMutationListener())
2344  L->DefaultMemberInitializerInstantiated(Instantiation);
2345 
2346  // Return true if the in-class initializer is still missing.
2347  return !Instantiation->getInClassInitializer();
2348 }
2349 
2350 namespace {
2351  /// \brief A partial specialization whose template arguments have matched
2352  /// a given template-id.
2353  struct PartialSpecMatchResult {
2355  TemplateArgumentList *Args;
2356  };
2357 }
2358 
2360  SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2361  if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2363  return true;
2364 
2366  ClassTemplateSpec->getSpecializedTemplate()
2367  ->getPartialSpecializations(PartialSpecs);
2368  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2369  TemplateDeductionInfo Info(Loc);
2370  if (!DeduceTemplateArguments(PartialSpecs[I],
2371  ClassTemplateSpec->getTemplateArgs(), Info))
2372  return true;
2373  }
2374 
2375  return false;
2376 }
2377 
2378 /// Get the instantiation pattern to use to instantiate the definition of a
2379 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2380 /// template or of a partial specialization).
2381 static CXXRecordDecl *
2383  Sema &S, SourceLocation PointOfInstantiation,
2384  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2385  TemplateSpecializationKind TSK, bool Complain) {
2386  Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2387  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2388  return nullptr;
2389 
2390  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2391  CXXRecordDecl *Pattern = nullptr;
2392 
2393  // C++ [temp.class.spec.match]p1:
2394  // When a class template is used in a context that requires an
2395  // instantiation of the class, it is necessary to determine
2396  // whether the instantiation is to be generated using the primary
2397  // template or one of the partial specializations. This is done by
2398  // matching the template arguments of the class template
2399  // specialization with the template argument lists of the partial
2400  // specializations.
2401  typedef PartialSpecMatchResult MatchResult;
2404  Template->getPartialSpecializations(PartialSpecs);
2405  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2406  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2407  ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2408  TemplateDeductionInfo Info(FailedCandidates.getLocation());
2410  Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2411  // Store the failed-deduction information for use in diagnostics, later.
2412  // TODO: Actually use the failed-deduction info?
2413  FailedCandidates.addCandidate().set(
2414  DeclAccessPair::make(Template, AS_public), Partial,
2415  MakeDeductionFailureInfo(S.Context, Result, Info));
2416  (void)Result;
2417  } else {
2418  Matched.push_back(PartialSpecMatchResult());
2419  Matched.back().Partial = Partial;
2420  Matched.back().Args = Info.take();
2421  }
2422  }
2423 
2424  // If we're dealing with a member template where the template parameters
2425  // have been instantiated, this provides the original template parameters
2426  // from which the member template's parameters were instantiated.
2427 
2428  if (Matched.size() >= 1) {
2429  SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2430  if (Matched.size() == 1) {
2431  // -- If exactly one matching specialization is found, the
2432  // instantiation is generated from that specialization.
2433  // We don't need to do anything for this.
2434  } else {
2435  // -- If more than one matching specialization is found, the
2436  // partial order rules (14.5.4.2) are used to determine
2437  // whether one of the specializations is more specialized
2438  // than the others. If none of the specializations is more
2439  // specialized than all of the other matching
2440  // specializations, then the use of the class template is
2441  // ambiguous and the program is ill-formed.
2442  for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2443  PEnd = Matched.end();
2444  P != PEnd; ++P) {
2446  P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
2447  Best = P;
2448  }
2449 
2450  // Determine if the best partial specialization is more specialized than
2451  // the others.
2452  bool Ambiguous = false;
2453  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2454  PEnd = Matched.end();
2455  P != PEnd; ++P) {
2456  if (P != Best &&
2457  S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2458  PointOfInstantiation) !=
2459  Best->Partial) {
2460  Ambiguous = true;
2461  break;
2462  }
2463  }
2464 
2465  if (Ambiguous) {
2466  // Partial ordering did not produce a clear winner. Complain.
2467  Inst.Clear();
2468  ClassTemplateSpec->setInvalidDecl();
2469  S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2470  << ClassTemplateSpec;
2471 
2472  // Print the matching partial specializations.
2473  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2474  PEnd = Matched.end();
2475  P != PEnd; ++P)
2476  S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2478  P->Partial->getTemplateParameters(), *P->Args);
2479 
2480  return nullptr;
2481  }
2482  }
2483 
2484  // Instantiate using the best class template partial specialization.
2485  ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2486  while (OrigPartialSpec->getInstantiatedFromMember()) {
2487  // If we've found an explicit specialization of this class template,
2488  // stop here and use that as the pattern.
2489  if (OrigPartialSpec->isMemberSpecialization())
2490  break;
2491 
2492  OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2493  }
2494 
2495  Pattern = OrigPartialSpec;
2496  ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2497  } else {
2498  // -- If no matches are found, the instantiation is generated
2499  // from the primary template.
2500  ClassTemplateDecl *OrigTemplate = Template;
2501  while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2502  // If we've found an explicit specialization of this class template,
2503  // stop here and use that as the pattern.
2504  if (OrigTemplate->isMemberSpecialization())
2505  break;
2506 
2507  OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2508  }
2509 
2510  Pattern = OrigTemplate->getTemplatedDecl();
2511  }
2512 
2513  return Pattern;
2514 }
2515 
2517  SourceLocation PointOfInstantiation,
2518  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2519  TemplateSpecializationKind TSK, bool Complain) {
2520  // Perform the actual instantiation on the canonical declaration.
2521  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2522  ClassTemplateSpec->getCanonicalDecl());
2523  if (ClassTemplateSpec->isInvalidDecl())
2524  return true;
2525 
2527  *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2528  if (!Pattern)
2529  return true;
2530 
2531  return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2532  getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2533  Complain);
2534 }
2535 
2536 /// \brief Instantiates the definitions of all of the member
2537 /// of the given class, which is an instantiation of a class template
2538 /// or a member class of a template.
2539 void
2541  CXXRecordDecl *Instantiation,
2542  const MultiLevelTemplateArgumentList &TemplateArgs,
2544  // FIXME: We need to notify the ASTMutationListener that we did all of these
2545  // things, in case we have an explicit instantiation definition in a PCM, a
2546  // module, or preamble, and the declaration is in an imported AST.
2547  assert(
2550  (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2551  "Unexpected template specialization kind!");
2552  for (auto *D : Instantiation->decls()) {
2553  bool SuppressNew = false;
2554  if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2555  if (FunctionDecl *Pattern
2556  = Function->getInstantiatedFromMemberFunction()) {
2557  MemberSpecializationInfo *MSInfo
2558  = Function->getMemberSpecializationInfo();
2559  assert(MSInfo && "No member specialization information?");
2560  if (MSInfo->getTemplateSpecializationKind()
2562  continue;
2563 
2564  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2565  Function,
2567  MSInfo->getPointOfInstantiation(),
2568  SuppressNew) ||
2569  SuppressNew)
2570  continue;
2571 
2572  // C++11 [temp.explicit]p8:
2573  // An explicit instantiation definition that names a class template
2574  // specialization explicitly instantiates the class template
2575  // specialization and is only an explicit instantiation definition
2576  // of members whose definition is visible at the point of
2577  // instantiation.
2578  if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2579  continue;
2580 
2581  Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2582 
2583  if (Function->isDefined()) {
2584  // Let the ASTConsumer know that this function has been explicitly
2585  // instantiated now, and its linkage might have changed.
2587  } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2588  InstantiateFunctionDefinition(PointOfInstantiation, Function);
2589  } else if (TSK == TSK_ImplicitInstantiation) {
2591  std::make_pair(Function, PointOfInstantiation));
2592  }
2593  }
2594  } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2595  if (isa<VarTemplateSpecializationDecl>(Var))
2596  continue;
2597 
2598  if (Var->isStaticDataMember()) {
2600  assert(MSInfo && "No member specialization information?");
2601  if (MSInfo->getTemplateSpecializationKind()
2603  continue;
2604 
2605  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2606  Var,
2608  MSInfo->getPointOfInstantiation(),
2609  SuppressNew) ||
2610  SuppressNew)
2611  continue;
2612 
2614  // C++0x [temp.explicit]p8:
2615  // An explicit instantiation definition that names a class template
2616  // specialization explicitly instantiates the class template
2617  // specialization and is only an explicit instantiation definition
2618  // of members whose definition is visible at the point of
2619  // instantiation.
2621  continue;
2622 
2623  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2624  InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2625  } else {
2626  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2627  }
2628  }
2629  } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2630  // Always skip the injected-class-name, along with any
2631  // redeclarations of nested classes, since both would cause us
2632  // to try to instantiate the members of a class twice.
2633  // Skip closure types; they'll get instantiated when we instantiate
2634  // the corresponding lambda-expression.
2635  if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2636  Record->isLambda())
2637  continue;
2638 
2639  MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2640  assert(MSInfo && "No member specialization information?");
2641 
2642  if (MSInfo->getTemplateSpecializationKind()
2644  continue;
2645 
2647  Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
2649  // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2650  // outer class doesn't affect the inner class.
2651  continue;
2652  }
2653 
2654  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2655  Record,
2657  MSInfo->getPointOfInstantiation(),
2658  SuppressNew) ||
2659  SuppressNew)
2660  continue;
2661 
2662  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2663  assert(Pattern && "Missing instantiated-from-template information");
2664 
2665  if (!Record->getDefinition()) {
2666  if (!Pattern->getDefinition()) {
2667  // C++0x [temp.explicit]p8:
2668  // An explicit instantiation definition that names a class template
2669  // specialization explicitly instantiates the class template
2670  // specialization and is only an explicit instantiation definition
2671  // of members whose definition is visible at the point of
2672  // instantiation.
2674  MSInfo->setTemplateSpecializationKind(TSK);
2675  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2676  }
2677 
2678  continue;
2679  }
2680 
2681  InstantiateClass(PointOfInstantiation, Record, Pattern,
2682  TemplateArgs,
2683  TSK);
2684  } else {
2686  Record->getTemplateSpecializationKind() ==
2688  Record->setTemplateSpecializationKind(TSK);
2689  MarkVTableUsed(PointOfInstantiation, Record, true);
2690  }
2691  }
2692 
2693  Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2694  if (Pattern)
2695  InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2696  TSK);
2697  } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2698  MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2699  assert(MSInfo && "No member specialization information?");
2700 
2701  if (MSInfo->getTemplateSpecializationKind()
2703  continue;
2704 
2706  PointOfInstantiation, TSK, Enum,
2708  MSInfo->getPointOfInstantiation(), SuppressNew) ||
2709  SuppressNew)
2710  continue;
2711 
2712  if (Enum->getDefinition())
2713  continue;
2714 
2715  EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2716  assert(Pattern && "Missing instantiated-from-template information");
2717 
2719  if (!Pattern->getDefinition())
2720  continue;
2721 
2722  InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2723  } else {
2724  MSInfo->setTemplateSpecializationKind(TSK);
2725  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2726  }
2727  } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2728  // No need to instantiate in-class initializers during explicit
2729  // instantiation.
2730  if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2731  CXXRecordDecl *ClassPattern =
2732  Instantiation->getTemplateInstantiationPattern();
2734  ClassPattern->lookup(Field->getDeclName());
2735  FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2736  InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2737  TemplateArgs);
2738  }
2739  }
2740  }
2741 }
2742 
2743 /// \brief Instantiate the definitions of all of the members of the
2744 /// given class template specialization, which was named as part of an
2745 /// explicit instantiation.
2746 void
2748  SourceLocation PointOfInstantiation,
2749  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2751  // C++0x [temp.explicit]p7:
2752  // An explicit instantiation that names a class template
2753  // specialization is an explicit instantion of the same kind
2754  // (declaration or definition) of each of its members (not
2755  // including members inherited from base classes) that has not
2756  // been previously explicitly specialized in the translation unit
2757  // containing the explicit instantiation, except as described
2758  // below.
2759  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2760  getTemplateInstantiationArgs(ClassTemplateSpec),
2761  TSK);
2762 }
2763 
2764 StmtResult
2766  if (!S)
2767  return S;
2768 
2769  TemplateInstantiator Instantiator(*this, TemplateArgs,
2770  SourceLocation(),
2771  DeclarationName());
2772  return Instantiator.TransformStmt(S);
2773 }
2774 
2775 ExprResult
2777  if (!E)
2778  return E;
2779 
2780  TemplateInstantiator Instantiator(*this, TemplateArgs,
2781  SourceLocation(),
2782  DeclarationName());
2783  return Instantiator.TransformExpr(E);
2784 }
2785 
2787  const MultiLevelTemplateArgumentList &TemplateArgs,
2788  bool CXXDirectInit) {
2789  TemplateInstantiator Instantiator(*this, TemplateArgs,
2790  SourceLocation(),
2791  DeclarationName());
2792  return Instantiator.TransformInitializer(Init, CXXDirectInit);
2793 }
2794 
2795 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2796  const MultiLevelTemplateArgumentList &TemplateArgs,
2797  SmallVectorImpl<Expr *> &Outputs) {
2798  if (Exprs.empty())
2799  return false;
2800 
2801  TemplateInstantiator Instantiator(*this, TemplateArgs,
2802  SourceLocation(),
2803  DeclarationName());
2804  return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2805  IsCall, Outputs);
2806 }
2807 
2810  const MultiLevelTemplateArgumentList &TemplateArgs) {
2811  if (!NNS)
2812  return NestedNameSpecifierLoc();
2813 
2814  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2815  DeclarationName());
2816  return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2817 }
2818 
2819 /// \brief Do template substitution on declaration name info.
2822  const MultiLevelTemplateArgumentList &TemplateArgs) {
2823  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2824  NameInfo.getName());
2825  return Instantiator.TransformDeclarationNameInfo(NameInfo);
2826 }
2827 
2830  TemplateName Name, SourceLocation Loc,
2831  const MultiLevelTemplateArgumentList &TemplateArgs) {
2832  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2833  DeclarationName());
2834  CXXScopeSpec SS;
2835  SS.Adopt(QualifierLoc);
2836  return Instantiator.TransformTemplateName(SS, Name, Loc);
2837 }
2838 
2839 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2840  TemplateArgumentListInfo &Result,
2841  const MultiLevelTemplateArgumentList &TemplateArgs) {
2842  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2843  DeclarationName());
2844 
2845  return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2846 }
2847 
2848 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2849  // When storing ParmVarDecls in the local instantiation scope, we always
2850  // want to use the ParmVarDecl from the canonical function declaration,
2851  // since the map is then valid for any redeclaration or definition of that
2852  // function.
2853  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2854  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2855  unsigned i = PV->getFunctionScopeIndex();
2856  // This parameter might be from a freestanding function type within the
2857  // function and isn't necessarily referring to one of FD's parameters.
2858  if (FD->getParamDecl(i) == PV)
2859  return FD->getCanonicalDecl()->getParamDecl(i);
2860  }
2861  }
2862  return D;
2863 }
2864 
2865 
2866 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2868  D = getCanonicalParmVarDecl(D);
2869  for (LocalInstantiationScope *Current = this; Current;
2870  Current = Current->Outer) {
2871 
2872  // Check if we found something within this scope.
2873  const Decl *CheckD = D;
2874  do {
2875  LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2876  if (Found != Current->LocalDecls.end())
2877  return &Found->second;
2878 
2879  // If this is a tag declaration, it's possible that we need to look for
2880  // a previous declaration.
2881  if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2882  CheckD = Tag->getPreviousDecl();
2883  else
2884  CheckD = nullptr;
2885  } while (CheckD);
2886 
2887  // If we aren't combined with our outer scope, we're done.
2888  if (!Current->CombineWithOuterScope)
2889  break;
2890  }
2891 
2892  // If we're performing a partial substitution during template argument
2893  // deduction, we may not have values for template parameters yet.
2894  if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2895  isa<TemplateTemplateParmDecl>(D))
2896  return nullptr;
2897 
2898  // Local types referenced prior to definition may require instantiation.
2899  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2900  if (RD->isLocalClass())
2901  return nullptr;
2902 
2903  // Enumeration types referenced prior to definition may appear as a result of
2904  // error recovery.
2905  if (isa<EnumDecl>(D))
2906  return nullptr;
2907 
2908  // If we didn't find the decl, then we either have a sema bug, or we have a
2909  // forward reference to a label declaration. Return null to indicate that
2910  // we have an uninstantiated label.
2911  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2912  return nullptr;
2913 }
2914 
2916  D = getCanonicalParmVarDecl(D);
2917  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2918  if (Stored.isNull()) {
2919 #ifndef NDEBUG
2920  // It should not be present in any surrounding scope either.
2922  while (Current->CombineWithOuterScope && Current->Outer) {
2923  Current = Current->Outer;
2924  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2925  "Instantiated local in inner and outer scopes");
2926  }
2927 #endif
2928  Stored = Inst;
2929  } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2930  Pack->push_back(cast<ParmVarDecl>(Inst));
2931  } else {
2932  assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2933  }
2934 }
2935 
2937  ParmVarDecl *Inst) {
2938  D = getCanonicalParmVarDecl(D);
2939  DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2940  Pack->push_back(Inst);
2941 }
2942 
2944 #ifndef NDEBUG
2945  // This should be the first time we've been told about this decl.
2946  for (LocalInstantiationScope *Current = this;
2947  Current && Current->CombineWithOuterScope; Current = Current->Outer)
2948  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2949  "Creating local pack after instantiation of local");
2950 #endif
2951 
2952  D = getCanonicalParmVarDecl(D);
2953  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2954  DeclArgumentPack *Pack = new DeclArgumentPack;
2955  Stored = Pack;
2956  ArgumentPacks.push_back(Pack);
2957 }
2958 
2960  const TemplateArgument *ExplicitArgs,
2961  unsigned NumExplicitArgs) {
2962  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2963  "Already have a partially-substituted pack");
2964  assert((!PartiallySubstitutedPack
2965  || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2966  "Wrong number of arguments in partially-substituted pack");
2967  PartiallySubstitutedPack = Pack;
2968  ArgsInPartiallySubstitutedPack = ExplicitArgs;
2969  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2970 }
2971 
2973  const TemplateArgument **ExplicitArgs,
2974  unsigned *NumExplicitArgs) const {
2975  if (ExplicitArgs)
2976  *ExplicitArgs = nullptr;
2977  if (NumExplicitArgs)
2978  *NumExplicitArgs = 0;
2979 
2980  for (const LocalInstantiationScope *Current = this; Current;
2981  Current = Current->Outer) {
2982  if (Current->PartiallySubstitutedPack) {
2983  if (ExplicitArgs)
2984  *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2985  if (NumExplicitArgs)
2986  *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2987 
2988  return Current->PartiallySubstitutedPack;
2989  }
2990 
2991  if (!Current->CombineWithOuterScope)
2992  break;
2993  }
2994 
2995  return nullptr;
2996 }
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.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1467
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 ...
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
ParmVarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:3904
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:7044
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
unsigned getDepth() const
Definition: Type.h:4024
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:497
no exception specification
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:1343
A (possibly-)qualified type.
Definition: Type.h:616
ASTConsumer & Consumer
Definition: Sema.h:306
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:6772
void InstantiatedLocal(const Decl *D, Decl *Inst)
base_class_range bases()
Definition: DeclCXX.h:737
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:202
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic...
Definition: Diagnostic.h:484
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:1803
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:111
const LangOptions & getLangOpts() const
Definition: Sema.h:1166
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:7054
bool isMemberSpecialization()
Determines whether this class template partial specialization template was a specialization of a memb...
Stmt - This represents one statement.
Definition: Stmt.h:60
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1537
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
Provides information about an attempted template argument deduction, whose success or failure was des...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4566
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...
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1487
The template argument is an expression, and we've not resolved it to one of the other forms yet...
Definition: TemplateBase.h:69
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
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:87
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1243
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2069
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:7102
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:922
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization...
Definition: Decl.h:3331
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:316
PtrTy get() const
Definition: Ownership.h:163
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation. ...
Definition: Sema.h:7113
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:7499
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1518
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1205
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:51
static void PrintTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, bool SkipBrackets=false)
Print a template argument list, including the '<' and '>' enclosing the template arguments...
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:112
A container of type source information.
Definition: Decl.h:62
unsigned getIndex() const
Definition: Type.h:4025
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:306
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:7008
iterator begin() const
Definition: ExprCXX.h:3905
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
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:7143
Expr * getInClassInitializer() const
getInClassInitializer - Get the C++11 in-class initializer for this member, or null if one has not be...
Definition: Decl.h:2489
InClassInitStyle getInClassInitStyle() const
getInClassInitStyle - Get the kind of (C++11) in-class initializer which this field has...
Definition: Decl.h:2473
IdentType getIdentType() const
Definition: Expr.h:1212
void ActOnFinishCXXNonNestedClass(Decl *D)
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:125
void InstantiatedLocalPackArg(const Decl *D, ParmVarDecl *Inst)
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10497
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:758
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1733
DiagnosticsEngine & Diags
Definition: Sema.h:307
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, unsigned ThisTypeQuals)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Represents a variable template specialization, which refers to a variable template with a given set o...
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:10446
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:4980
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:4028
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition: Template.h:483
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:50
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:6996
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1009
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1575
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1434
unsigned getNumArgs() const
Retrieve the number of template arguments.
Definition: Type.h:4390
SourceLocation getLocation() const
Definition: Expr.h:1046
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1392
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
bool isVoidType() const
Definition: Type.h:5906
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1377
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3354
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:7302
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1549
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
DeclarationName getName() const
getName - Returns the embedded declaration name.
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:7419
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:3844
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2510
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1813
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
A C++ nested-name-specifier augmented with source location information.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1146
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
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:12978
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2366
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:100
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:751
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation, for substitutions of prior template arguments.
Definition: Sema.h:7059
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3675
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:695
bool isTranslationUnit() const
Definition: DeclBase.h:1364
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:3150
TagKind getTagKind() const
Definition: Decl.h:3019
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)
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:3806
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:509
Describes a module or submodule.
Definition: Module.h:57
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:947
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:7037
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3113
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:505
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:643
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
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:3818
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
A convenient class for passing around template argument information.
Definition: TemplateBase.h:524
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
virtual void printName(raw_ostream &os) const
Definition: Decl.cpp:1447
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:807
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:7118
ParmVarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:3912
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:800
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced...
Definition: Sema.h:7151
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:7051
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
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.
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:671
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
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:796
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1519
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
SourceLocation getLocation() const
Definition: Expr.h:1214
detail::InMemoryDirectory::const_iterator I
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1022
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:982
QualType getType() const
Definition: Decl.h:589
void setLocStart(SourceLocation L)
Definition: Decl.h:2667
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:841
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:7165
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:4138
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:7524
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
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:7017
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:269
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3129
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:1336
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
bool isParameterPack() const
Determine whether this parameter is actually a function parameter pack.
Definition: Decl.cpp:2529
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:3909
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
ASTContext * Context
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:2940
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2392
We are instantiating a template declaration.
Definition: Sema.h:7001
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1674
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
int * Depth
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:493
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
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...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:580
Expr - This represents one expression.
Definition: Expr.h:105
Defines the clang::LangOptions interface.
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4516
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:667
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
Declaration of a template type parameter.
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:7024
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4503
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:54
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:956
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:7134
SourceLocation getLocation() const
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:213
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3347
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional< unsigned > NumExpansions, bool ExpectParameterPack)
DeclContext * getDeclContext()
Definition: DeclBase.h:416
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.
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a C++ template name within the type system.
Definition: TemplateName.h:176
NonTypeTemplateParmDecl * getParameterPack() const
Retrieve the non-type template parameter pack being substituted.
Definition: ExprCXX.h:3832
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:337
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:114
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:849
void CheckCompletedCXXClass(CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:72
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1797
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1294
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:42
void setLocation(SourceLocation L)
Definition: DeclBase.h:408
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3751
ValueDecl * getDecl()
Definition: Expr.h:1038
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:148
SourceLocation getLocEnd() const LLVM_READONLY
Definition: TypeLoc.h:138
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:661
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:264
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...
SourceLocation getParameterPackLocation() const
Retrieve the location of the parameter pack name.
Definition: ExprCXX.h:3835
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:480
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all otuer scopes, down to the given outermost scope. ...
Definition: Template.h:338
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:222
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
We are declaring an implicit special member function.
Definition: Sema.h:7040
Kind
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:145
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3220
A stack object to be created when performing template instantiation.
Definition: Sema.h:7202
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs)
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:66
Encodes a location in the source.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:259
void setBraceRange(SourceRange R)
Definition: Decl.h:2936
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:7082
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:119
SourceRange getBraceRange() const
Definition: Decl.h:2935
void InstantiateStaticDataMemberDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false)
Instantiate the definition of the given variable from its template.
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:487
reference front() const
Definition: DeclBase.h:1188
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2816
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:6998
TemplateArgument getArgumentPack() const
Retrieve the template argument pack containing the substituted template arguments.
Definition: ExprCXX.cpp:1323
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1903
SourceLocation getNameLoc() const
Definition: TypeLoc.h:502
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:7033
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
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...
void setTagKind(TagKind TK)
Definition: Decl.h:3023
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
ParmVarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:3897
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:7105
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:166
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1507
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:160
bool isFileContext() const
Definition: DeclBase.h:1360
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:3576
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization, returns the templated static data member from which it was instantiated.
Definition: Decl.cpp:2356
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList)
Definition: SemaDecl.cpp:14832
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:2421
iterator end() const
Definition: ExprCXX.h:3906
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1566
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:242
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2735
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.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.
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template...
Definition: Decl.cpp:2401
QualType getType() const
Definition: Expr.h:127
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
Represents a reference to a function parameter pack that has been substituted but not yet expanded...
Definition: ExprCXX.h:3868
Represents a template argument.
Definition: TemplateBase.h:40
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1365
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:235
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument. ...
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:355
TagTypeKind
The kind of a tag type.
Definition: Type.h:4488
llvm::PointerUnion3< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:40
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:7159
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1185
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1215
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:477
StringRef Name
Definition: USRFinder.cpp:123
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:378
bool hasUnparsedDefaultArg() const
hasUnparsedDefaultArg - Determines whether this parameter has a default argument that has not yet bee...
Definition: Decl.h:1545
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:2126
We are instantiating a default argument for a function.
Definition: Sema.h:7013
bool isInvalidDecl() const
Definition: DeclBase.h:532
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:505
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1158
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:156
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1650
bool isParameterPack() const
Definition: Type.h:4026
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:617
DeclarationName - The name of a declaration.
Expr * getDefaultArg()
Definition: Decl.cpp:2473
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:2207
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:7087
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:792
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:216
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:819
EnumDecl - Represents an enum.
Definition: Decl.h:3102
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1481
detail::InMemoryDirectory::const_iterator E
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:142
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2087
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:3900
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:11805
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool hasInheritedDefaultArg() const
Definition: Decl.h:1562
const TemplateArgument * getArgs() const
Retrieve the template arguments.
Definition: Type.h:4385
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:428
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:38
void setUnparsedDefaultArg()
setUnparsedDefaultArg - Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1558
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2515
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
Definition: Sema.h:2100
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:635
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:152
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a parameter pack.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:291
bool isNull() const
Determine whether this template name is NULL.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:1068
The template argument is a type.
Definition: TemplateBase.h:48
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
The template argument is actually a parameter pack.
Definition: TemplateBase.h:72
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1065
Represents a base class of a C++ class.
Definition: DeclCXX.h:158
const Expr * Replacement
Definition: AttributeList.h:59
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:304
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:7048
bool isUsable() const
Definition: Ownership.h:160
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ParmVarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ParmVarDecl * > Params)
Definition: ExprCXX.cpp:1340
A template argument list.
Definition: DeclTemplate.h:195
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:253
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:146
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:336
FormatToken * Current
Represents a C++ struct/union/class.
Definition: DeclCXX.h:267
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:861
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA)
Definition: Template.h:466
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...
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:595
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:317
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:127
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:410
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:247
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:7029
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1417
ExprResult ExprError()
Definition: Ownership.h:268
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:953
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:402
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4297
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:675
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:19
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.
StringRef getKindName() const
Definition: Decl.h:3015
Wrapper for template type parameters.
Definition: TypeLoc.h:706
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:7298
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:407
ASTContext & Context
Definition: Sema.h:305
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
NamedDecl * getAsNamedDecl(TemplateParameter P)
EnumDecl * getDefinition() const
Definition: Decl.h:3171
No keyword precedes the qualified type name.
Definition: Type.h:4518
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:683
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror...
Definition: Diagnostic.h:664
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:640
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:257
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3254
Declaration of a template function.
Definition: DeclTemplate.h:939
const NamedDecl * Result
Definition: USRFinder.cpp:70
Attr - This represents one attribute.
Definition: Attr.h:43
std::vector< const ClassTemplatePartialSpecializationDecl * > PartialSpecs
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
Definition: Decl.h:2528
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
bool hasInClassInitializer() const
hasInClassInitializer - Determine whether this member has a C++11 in-class initializer.
Definition: Decl.h:2481
A RAII object to temporarily push a declaration context.
Definition: Sema.h:684
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...