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