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