1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template instantiation.
11 //===----------------------------------------------------------------------===/
13 #include "clang/Sema/SemaInternal.h"
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/PrettyDeclStackTrace.h"
25 #include "clang/Sema/Template.h"
26 #include "clang/Sema/TemplateDeduction.h"
28 using namespace clang;
31 //===----------------------------------------------------------------------===/
32 // Template Instantiation Support
33 //===----------------------------------------------------------------------===/
35 /// \brief Retrieve the template argument list(s) that should be used to
36 /// instantiate the definition of the given declaration.
38 /// \param D the declaration for which we are computing template instantiation
41 /// \param Innermost if non-NULL, the innermost template argument list.
43 /// \param RelativeToPrimary true if we should get the template
44 /// arguments relative to the primary template, even when we're
45 /// dealing with a specialization. This is only relevant for function
46 /// template specializations.
48 /// \param Pattern If non-NULL, indicates the pattern from which we will be
49 /// instantiating the definition of the given declaration, \p D. This is
50 /// used to determine the proper set of template instantiation arguments for
51 /// friend function template specializations.
52 MultiLevelTemplateArgumentList
53 Sema::getTemplateInstantiationArgs(NamedDecl *D,
54 const TemplateArgumentList *Innermost,
55 bool RelativeToPrimary,
56 const FunctionDecl *Pattern) {
57 // Accumulate the set of template argument lists in this structure.
58 MultiLevelTemplateArgumentList Result;
61 Result.addOuterTemplateArguments(Innermost);
63 DeclContext *Ctx = dyn_cast<DeclContext>(D);
65 Ctx = D->getDeclContext();
67 // Add template arguments from a variable template instantiation.
68 if (VarTemplateSpecializationDecl *Spec =
69 dyn_cast<VarTemplateSpecializationDecl>(D)) {
70 // We're done when we hit an explicit specialization.
71 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
72 !isa<VarTemplatePartialSpecializationDecl>(Spec))
75 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77 // If this variable template specialization was instantiated from a
78 // specialized member that is a variable template, we're done.
79 assert(Spec->getSpecializedTemplate() && "No variable template?");
80 llvm::PointerUnion<VarTemplateDecl*,
81 VarTemplatePartialSpecializationDecl*> Specialized
82 = Spec->getSpecializedTemplateOrPartial();
83 if (VarTemplatePartialSpecializationDecl *Partial =
84 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
85 if (Partial->isMemberSpecialization())
88 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
89 if (Tmpl->isMemberSpecialization())
94 // If we have a template template parameter with translation unit context,
95 // then we're performing substitution into a default template argument of
96 // this template template parameter before we've constructed the template
97 // that will own this template template parameter. In this case, we
98 // use empty template parameter lists for all of the outer templates
99 // to avoid performing any substitutions.
100 if (Ctx->isTranslationUnit()) {
101 if (TemplateTemplateParmDecl *TTP
102 = dyn_cast<TemplateTemplateParmDecl>(D)) {
103 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
104 Result.addOuterTemplateArguments(None);
110 while (!Ctx->isFileContext()) {
111 // Add template arguments from a class template instantiation.
112 if (ClassTemplateSpecializationDecl *Spec
113 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
114 // We're done when we hit an explicit specialization.
115 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
116 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
119 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
121 // If this class template specialization was instantiated from a
122 // specialized member that is a class template, we're done.
123 assert(Spec->getSpecializedTemplate() && "No class template?");
124 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
127 // Add template arguments from a function template specialization.
128 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
129 if (!RelativeToPrimary &&
130 (Function->getTemplateSpecializationKind() ==
131 TSK_ExplicitSpecialization &&
132 !Function->getClassScopeSpecializationPattern()))
135 if (const TemplateArgumentList *TemplateArgs
136 = Function->getTemplateSpecializationArgs()) {
137 // Add the template arguments for this specialization.
138 Result.addOuterTemplateArguments(TemplateArgs);
140 // If this function was instantiated from a specialized member that is
141 // a function template, we're done.
142 assert(Function->getPrimaryTemplate() && "No function template?");
143 if (Function->getPrimaryTemplate()->isMemberSpecialization())
146 // If this function is a generic lambda specialization, we are done.
147 if (isGenericLambdaCallOperatorSpecialization(Function))
150 } else if (FunctionTemplateDecl *FunTmpl
151 = Function->getDescribedFunctionTemplate()) {
152 // Add the "injected" template arguments.
153 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
156 // If this is a friend declaration and it declares an entity at
157 // namespace scope, take arguments from its lexical parent
158 // instead of its semantic parent, unless of course the pattern we're
159 // instantiating actually comes from the file's context!
160 if (Function->getFriendObjectKind() &&
161 Function->getDeclContext()->isFileContext() &&
162 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
163 Ctx = Function->getLexicalDeclContext();
164 RelativeToPrimary = false;
167 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
168 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
169 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
170 const TemplateSpecializationType *TST =
171 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
172 Result.addOuterTemplateArguments(
173 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
174 if (ClassTemplate->isMemberSpecialization())
179 Ctx = Ctx->getParent();
180 RelativeToPrimary = false;
186 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
188 case TemplateInstantiation:
189 case ExceptionSpecInstantiation:
190 case DefaultTemplateArgumentInstantiation:
191 case DefaultFunctionArgumentInstantiation:
192 case ExplicitTemplateArgumentSubstitution:
193 case DeducedTemplateArgumentSubstitution:
194 case PriorTemplateArgumentSubstitution:
197 case DefaultTemplateArgumentChecking:
201 llvm_unreachable("Invalid InstantiationKind!");
204 Sema::InstantiatingTemplate::InstantiatingTemplate(
205 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
206 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
207 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
208 sema::TemplateDeductionInfo *DeductionInfo)
209 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
210 SemaRef.InNonInstantiationSFINAEContext) {
211 // Don't allow further instantiation if a fatal error has occcured. Any
212 // diagnostics we might have raised will not be visible.
213 if (SemaRef.Diags.hasFatalErrorOccurred()) {
217 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
219 ActiveTemplateInstantiation Inst;
221 Inst.PointOfInstantiation = PointOfInstantiation;
222 Inst.Entity = Entity;
223 Inst.Template = Template;
224 Inst.TemplateArgs = TemplateArgs.data();
225 Inst.NumTemplateArgs = TemplateArgs.size();
226 Inst.DeductionInfo = DeductionInfo;
227 Inst.InstantiationRange = InstantiationRange;
228 AlreadyInstantiating =
229 !SemaRef.InstantiatingSpecializations
230 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
232 SemaRef.InNonInstantiationSFINAEContext = false;
233 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
234 if (!Inst.isInstantiationRecord())
235 ++SemaRef.NonInstantiationEntries;
239 Sema::InstantiatingTemplate::InstantiatingTemplate(
240 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
241 SourceRange InstantiationRange)
242 : InstantiatingTemplate(SemaRef,
243 ActiveTemplateInstantiation::TemplateInstantiation,
244 PointOfInstantiation, InstantiationRange, Entity) {}
246 Sema::InstantiatingTemplate::InstantiatingTemplate(
247 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
248 ExceptionSpecification, SourceRange InstantiationRange)
249 : InstantiatingTemplate(
250 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
251 PointOfInstantiation, InstantiationRange, Entity) {}
253 Sema::InstantiatingTemplate::InstantiatingTemplate(
254 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
255 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
256 SourceRange InstantiationRange)
257 : InstantiatingTemplate(
259 ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
260 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
261 Template, TemplateArgs) {}
263 Sema::InstantiatingTemplate::InstantiatingTemplate(
264 Sema &SemaRef, SourceLocation PointOfInstantiation,
265 FunctionTemplateDecl *FunctionTemplate,
266 ArrayRef<TemplateArgument> TemplateArgs,
267 ActiveTemplateInstantiation::InstantiationKind Kind,
268 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
269 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
270 InstantiationRange, FunctionTemplate, nullptr,
271 TemplateArgs, &DeductionInfo) {
273 Kind == ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution ||
274 Kind == ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution);
277 Sema::InstantiatingTemplate::InstantiatingTemplate(
278 Sema &SemaRef, SourceLocation PointOfInstantiation,
279 ClassTemplatePartialSpecializationDecl *PartialSpec,
280 ArrayRef<TemplateArgument> TemplateArgs,
281 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
282 : InstantiatingTemplate(
284 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
285 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
286 TemplateArgs, &DeductionInfo) {}
288 Sema::InstantiatingTemplate::InstantiatingTemplate(
289 Sema &SemaRef, SourceLocation PointOfInstantiation,
290 VarTemplatePartialSpecializationDecl *PartialSpec,
291 ArrayRef<TemplateArgument> TemplateArgs,
292 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
293 : InstantiatingTemplate(
295 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
296 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
297 TemplateArgs, &DeductionInfo) {}
299 Sema::InstantiatingTemplate::InstantiatingTemplate(
300 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
301 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
302 : InstantiatingTemplate(
304 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
305 PointOfInstantiation, InstantiationRange, Param, nullptr,
308 Sema::InstantiatingTemplate::InstantiatingTemplate(
309 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
310 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
311 SourceRange InstantiationRange)
312 : InstantiatingTemplate(
314 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
315 PointOfInstantiation, InstantiationRange, Param, Template,
318 Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
320 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
321 SourceRange InstantiationRange)
322 : InstantiatingTemplate(
324 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
325 PointOfInstantiation, InstantiationRange, Param, Template,
328 Sema::InstantiatingTemplate::InstantiatingTemplate(
329 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
330 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
331 SourceRange InstantiationRange)
332 : InstantiatingTemplate(
333 SemaRef, ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
334 PointOfInstantiation, InstantiationRange, Param, Template,
337 void Sema::InstantiatingTemplate::Clear() {
339 auto &Active = SemaRef.ActiveTemplateInstantiations.back();
340 if (!Active.isInstantiationRecord()) {
341 assert(SemaRef.NonInstantiationEntries > 0);
342 --SemaRef.NonInstantiationEntries;
344 SemaRef.InNonInstantiationSFINAEContext
345 = SavedInNonInstantiationSFINAEContext;
347 // Name lookup no longer looks in this template's defining module.
348 assert(SemaRef.ActiveTemplateInstantiations.size() >=
349 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
350 "forgot to remove a lookup module for a template instantiation");
351 if (SemaRef.ActiveTemplateInstantiations.size() ==
352 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
353 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
354 SemaRef.LookupModulesCache.erase(M);
355 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
358 if (!AlreadyInstantiating)
359 SemaRef.InstantiatingSpecializations.erase(
360 std::make_pair(Active.Entity, Active.Kind));
362 SemaRef.ActiveTemplateInstantiations.pop_back();
367 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
368 SourceLocation PointOfInstantiation,
369 SourceRange InstantiationRange) {
370 assert(SemaRef.NonInstantiationEntries <=
371 SemaRef.ActiveTemplateInstantiations.size());
372 if ((SemaRef.ActiveTemplateInstantiations.size() -
373 SemaRef.NonInstantiationEntries)
374 <= SemaRef.getLangOpts().InstantiationDepth)
377 SemaRef.Diag(PointOfInstantiation,
378 diag::err_template_recursion_depth_exceeded)
379 << SemaRef.getLangOpts().InstantiationDepth
380 << InstantiationRange;
381 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
382 << SemaRef.getLangOpts().InstantiationDepth;
386 /// \brief Prints the current instantiation stack through a series of
388 void Sema::PrintInstantiationStack() {
389 // Determine which template instantiations to skip, if any.
390 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
391 unsigned Limit = Diags.getTemplateBacktraceLimit();
392 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
393 SkipStart = Limit / 2 + Limit % 2;
394 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
397 // FIXME: In all of these cases, we need to show the template arguments
398 unsigned InstantiationIdx = 0;
399 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
400 Active = ActiveTemplateInstantiations.rbegin(),
401 ActiveEnd = ActiveTemplateInstantiations.rend();
403 ++Active, ++InstantiationIdx) {
404 // Skip this instantiation?
405 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
406 if (InstantiationIdx == SkipStart) {
407 // Note that we're skipping instantiations.
408 Diags.Report(Active->PointOfInstantiation,
409 diag::note_instantiation_contexts_suppressed)
410 << unsigned(ActiveTemplateInstantiations.size() - Limit);
415 switch (Active->Kind) {
416 case ActiveTemplateInstantiation::TemplateInstantiation: {
417 Decl *D = Active->Entity;
418 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
419 unsigned DiagID = diag::note_template_member_class_here;
420 if (isa<ClassTemplateSpecializationDecl>(Record))
421 DiagID = diag::note_template_class_instantiation_here;
422 Diags.Report(Active->PointOfInstantiation, DiagID)
423 << Context.getTypeDeclType(Record)
424 << Active->InstantiationRange;
425 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
427 if (Function->getPrimaryTemplate())
428 DiagID = diag::note_function_template_spec_here;
430 DiagID = diag::note_template_member_function_here;
431 Diags.Report(Active->PointOfInstantiation, DiagID)
433 << Active->InstantiationRange;
434 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
435 Diags.Report(Active->PointOfInstantiation,
436 VD->isStaticDataMember()?
437 diag::note_template_static_data_member_def_here
438 : diag::note_template_variable_def_here)
440 << Active->InstantiationRange;
441 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
442 Diags.Report(Active->PointOfInstantiation,
443 diag::note_template_enum_def_here)
445 << Active->InstantiationRange;
446 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
447 Diags.Report(Active->PointOfInstantiation,
448 diag::note_template_nsdmi_here)
449 << FD << Active->InstantiationRange;
451 Diags.Report(Active->PointOfInstantiation,
452 diag::note_template_type_alias_instantiation_here)
453 << cast<TypeAliasTemplateDecl>(D)
454 << Active->InstantiationRange;
459 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
460 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
461 SmallVector<char, 128> TemplateArgsStr;
462 llvm::raw_svector_ostream OS(TemplateArgsStr);
463 Template->printName(OS);
464 TemplateSpecializationType::PrintTemplateArgumentList(
465 OS, Active->template_arguments(), getPrintingPolicy());
466 Diags.Report(Active->PointOfInstantiation,
467 diag::note_default_arg_instantiation_here)
469 << Active->InstantiationRange;
473 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
474 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
475 Diags.Report(Active->PointOfInstantiation,
476 diag::note_explicit_template_arg_substitution_here)
478 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
479 Active->TemplateArgs,
480 Active->NumTemplateArgs)
481 << Active->InstantiationRange;
485 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
486 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
487 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
488 Diags.Report(Active->PointOfInstantiation,
489 diag::note_partial_spec_deduct_instantiation_here)
490 << Context.getTypeDeclType(PartialSpec)
491 << getTemplateArgumentBindingsText(
492 PartialSpec->getTemplateParameters(),
493 Active->TemplateArgs,
494 Active->NumTemplateArgs)
495 << Active->InstantiationRange;
497 FunctionTemplateDecl *FnTmpl
498 = cast<FunctionTemplateDecl>(Active->Entity);
499 Diags.Report(Active->PointOfInstantiation,
500 diag::note_function_template_deduction_instantiation_here)
502 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
503 Active->TemplateArgs,
504 Active->NumTemplateArgs)
505 << Active->InstantiationRange;
509 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
510 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
511 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
513 SmallVector<char, 128> TemplateArgsStr;
514 llvm::raw_svector_ostream OS(TemplateArgsStr);
516 TemplateSpecializationType::PrintTemplateArgumentList(
517 OS, Active->template_arguments(), getPrintingPolicy());
518 Diags.Report(Active->PointOfInstantiation,
519 diag::note_default_function_arg_instantiation_here)
521 << Active->InstantiationRange;
525 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
526 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
528 if (!Parm->getName().empty())
529 Name = std::string(" '") + Parm->getName().str() + "'";
531 TemplateParameterList *TemplateParams = nullptr;
532 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
533 TemplateParams = Template->getTemplateParameters();
536 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
537 ->getTemplateParameters();
538 Diags.Report(Active->PointOfInstantiation,
539 diag::note_prior_template_arg_substitution)
540 << isa<TemplateTemplateParmDecl>(Parm)
542 << getTemplateArgumentBindingsText(TemplateParams,
543 Active->TemplateArgs,
544 Active->NumTemplateArgs)
545 << Active->InstantiationRange;
549 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
550 TemplateParameterList *TemplateParams = nullptr;
551 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
552 TemplateParams = Template->getTemplateParameters();
555 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
556 ->getTemplateParameters();
558 Diags.Report(Active->PointOfInstantiation,
559 diag::note_template_default_arg_checking)
560 << getTemplateArgumentBindingsText(TemplateParams,
561 Active->TemplateArgs,
562 Active->NumTemplateArgs)
563 << Active->InstantiationRange;
567 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
568 Diags.Report(Active->PointOfInstantiation,
569 diag::note_template_exception_spec_instantiation_here)
570 << cast<FunctionDecl>(Active->Entity)
571 << Active->InstantiationRange;
577 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
578 if (InNonInstantiationSFINAEContext)
579 return Optional<TemplateDeductionInfo *>(nullptr);
581 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
582 Active = ActiveTemplateInstantiations.rbegin(),
583 ActiveEnd = ActiveTemplateInstantiations.rend();
587 switch(Active->Kind) {
588 case ActiveTemplateInstantiation::TemplateInstantiation:
589 // An instantiation of an alias template may or may not be a SFINAE
590 // context, depending on what else is on the stack.
591 if (isa<TypeAliasTemplateDecl>(Active->Entity))
594 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
595 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
596 // This is a template instantiation, so there is no SFINAE.
599 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
600 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
601 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
602 // A default template argument instantiation and substitution into
603 // template parameters with arguments for prior parameters may or may
604 // not be a SFINAE context; look further up the stack.
607 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
608 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
609 // We're either substitution explicitly-specified template arguments
610 // or deduced template arguments, so SFINAE applies.
611 assert(Active->DeductionInfo && "Missing deduction info pointer");
612 return Active->DeductionInfo;
619 /// \brief Retrieve the depth and index of a parameter pack.
620 static std::pair<unsigned, unsigned>
621 getDepthAndIndex(NamedDecl *ND) {
622 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
623 return std::make_pair(TTP->getDepth(), TTP->getIndex());
625 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
626 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
628 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
629 return std::make_pair(TTP->getDepth(), TTP->getIndex());
632 //===----------------------------------------------------------------------===/
633 // Template Instantiation for Types
634 //===----------------------------------------------------------------------===/
636 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
637 const MultiLevelTemplateArgumentList &TemplateArgs;
639 DeclarationName Entity;
642 typedef TreeTransform<TemplateInstantiator> inherited;
644 TemplateInstantiator(Sema &SemaRef,
645 const MultiLevelTemplateArgumentList &TemplateArgs,
647 DeclarationName Entity)
648 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
651 /// \brief Determine whether the given type \p T has already been
654 /// For the purposes of template instantiation, a type has already been
655 /// transformed if it is NULL or if it is not dependent.
656 bool AlreadyTransformed(QualType T);
658 /// \brief Returns the location of the entity being instantiated, if known.
659 SourceLocation getBaseLocation() { return Loc; }
661 /// \brief Returns the name of the entity being instantiated, if any.
662 DeclarationName getBaseEntity() { return Entity; }
664 /// \brief Sets the "base" location and entity when that
665 /// information is known based on another transformation.
666 void setBase(SourceLocation Loc, DeclarationName Entity) {
668 this->Entity = Entity;
671 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
672 SourceRange PatternRange,
673 ArrayRef<UnexpandedParameterPack> Unexpanded,
674 bool &ShouldExpand, bool &RetainExpansion,
675 Optional<unsigned> &NumExpansions) {
676 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
677 PatternRange, Unexpanded,
684 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
685 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
688 TemplateArgument ForgetPartiallySubstitutedPack() {
689 TemplateArgument Result;
690 if (NamedDecl *PartialPack
691 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
692 MultiLevelTemplateArgumentList &TemplateArgs
693 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
694 unsigned Depth, Index;
695 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
696 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
697 Result = TemplateArgs(Depth, Index);
698 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
705 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
709 if (NamedDecl *PartialPack
710 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
711 MultiLevelTemplateArgumentList &TemplateArgs
712 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
713 unsigned Depth, Index;
714 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
715 TemplateArgs.setArgument(Depth, Index, Arg);
719 /// \brief Transform the given declaration by instantiating a reference to
720 /// this declaration.
721 Decl *TransformDecl(SourceLocation Loc, Decl *D);
723 void transformAttrs(Decl *Old, Decl *New) {
724 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
727 void transformedLocalDecl(Decl *Old, Decl *New) {
728 // If we've instantiated the call operator of a lambda or the call
729 // operator template of a generic lambda, update the "instantiation of"
731 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
732 if (NewMD && isLambdaCallOperator(NewMD)) {
733 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
734 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
735 NewTD->setInstantiatedFromMemberTemplate(
736 OldMD->getDescribedFunctionTemplate());
738 NewMD->setInstantiationOfMemberFunction(OldMD,
739 TSK_ImplicitInstantiation);
742 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
744 // We recreated a local declaration, but not by instantiating it. There
745 // may be pending dependent diagnostics to produce.
746 if (auto *DC = dyn_cast<DeclContext>(Old))
747 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
750 /// \brief Transform the definition of the given declaration by
751 /// instantiating it.
752 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
754 /// \brief Transform the first qualifier within a scope by instantiating the
756 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
758 /// \brief Rebuild the exception declaration and register the declaration
759 /// as an instantiated local.
760 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
761 TypeSourceInfo *Declarator,
762 SourceLocation StartLoc,
763 SourceLocation NameLoc,
764 IdentifierInfo *Name);
766 /// \brief Rebuild the Objective-C exception declaration and register the
767 /// declaration as an instantiated local.
768 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
769 TypeSourceInfo *TSInfo, QualType T);
771 /// \brief Check for tag mismatches when instantiating an
773 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
774 ElaboratedTypeKeyword Keyword,
775 NestedNameSpecifierLoc QualifierLoc,
779 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
780 SourceLocation NameLoc,
781 QualType ObjectType = QualType(),
782 NamedDecl *FirstQualifierInScope = nullptr);
784 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
786 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
787 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
788 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
790 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
791 NonTypeTemplateParmDecl *D);
792 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
793 SubstNonTypeTemplateParmPackExpr *E);
795 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
796 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
798 /// \brief Transform a reference to a function parameter pack.
799 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
802 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
803 /// expand a function parameter pack reference which refers to an expanded
805 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
807 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
808 FunctionProtoTypeLoc TL) {
809 // Call the base version; it will forward to our overridden version below.
810 return inherited::TransformFunctionProtoType(TLB, TL);
813 template<typename Fn>
814 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
815 FunctionProtoTypeLoc TL,
816 CXXRecordDecl *ThisContext,
817 unsigned ThisTypeQuals,
818 Fn TransformExceptionSpec);
820 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
822 Optional<unsigned> NumExpansions,
823 bool ExpectParameterPack);
825 /// \brief Transforms a template type parameter type by performing
826 /// substitution of the corresponding template type argument.
827 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
828 TemplateTypeParmTypeLoc TL);
830 /// \brief Transforms an already-substituted template type parameter pack
831 /// into either itself (if we aren't substituting into its pack expansion)
832 /// or the appropriate substituted argument.
833 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
834 SubstTemplateTypeParmPackTypeLoc TL);
836 ExprResult TransformLambdaExpr(LambdaExpr *E) {
837 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
838 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
841 TemplateParameterList *TransformTemplateParameterList(
842 TemplateParameterList *OrigTPL) {
843 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
845 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
846 TemplateDeclInstantiator DeclInstantiator(getSema(),
847 /* DeclContext *Owner */ Owner, TemplateArgs);
848 return DeclInstantiator.SubstTemplateParams(OrigTPL);
851 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
853 TemplateArgument arg);
857 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
861 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
864 getSema().MarkDeclarationsReferencedInType(Loc, T);
868 static TemplateArgument
869 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
870 assert(S.ArgumentPackSubstitutionIndex >= 0);
871 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
872 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
873 if (Arg.isPackExpansion())
874 Arg = Arg.getPackExpansionPattern();
878 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
882 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
883 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
884 // If the corresponding template argument is NULL or non-existent, it's
885 // because we are performing instantiation from explicitly-specified
886 // template arguments in a function template, but there were some
887 // arguments left unspecified.
888 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
892 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
894 if (TTP->isParameterPack()) {
895 assert(Arg.getKind() == TemplateArgument::Pack &&
896 "Missing argument pack");
897 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
900 TemplateName Template = Arg.getAsTemplate();
901 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
902 "Wrong kind of template template argument");
903 return Template.getAsTemplateDecl();
906 // Fall through to find the instantiated declaration for this template
907 // template parameter.
910 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
913 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
914 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
918 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
923 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
924 SourceLocation Loc) {
925 // If the first part of the nested-name-specifier was a template type
926 // parameter, instantiate that type parameter down to a tag type.
927 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
928 const TemplateTypeParmType *TTP
929 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
931 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
932 // FIXME: This needs testing w/ member access expressions.
933 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
935 if (TTP->isParameterPack()) {
936 assert(Arg.getKind() == TemplateArgument::Pack &&
937 "Missing argument pack");
939 if (getSema().ArgumentPackSubstitutionIndex == -1)
942 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
945 QualType T = Arg.getAsType();
947 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
949 if (const TagType *Tag = T->getAs<TagType>())
950 return Tag->getDecl();
952 // The resulting type is not a tag; complain.
953 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
958 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
962 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
963 TypeSourceInfo *Declarator,
964 SourceLocation StartLoc,
965 SourceLocation NameLoc,
966 IdentifierInfo *Name) {
967 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
968 StartLoc, NameLoc, Name);
970 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
974 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
975 TypeSourceInfo *TSInfo,
977 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
979 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
984 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
985 ElaboratedTypeKeyword Keyword,
986 NestedNameSpecifierLoc QualifierLoc,
988 if (const TagType *TT = T->getAs<TagType>()) {
989 TagDecl* TD = TT->getDecl();
991 SourceLocation TagLocation = KeywordLoc;
993 IdentifierInfo *Id = TD->getIdentifier();
995 // TODO: should we even warn on struct/class mismatches for this? Seems
996 // like it's likely to produce a lot of spurious errors.
997 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
998 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
999 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1001 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1003 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1005 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1010 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1016 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1018 SourceLocation NameLoc,
1019 QualType ObjectType,
1020 NamedDecl *FirstQualifierInScope) {
1021 if (TemplateTemplateParmDecl *TTP
1022 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1023 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1024 // If the corresponding template argument is NULL or non-existent, it's
1025 // because we are performing instantiation from explicitly-specified
1026 // template arguments in a function template, but there were some
1027 // arguments left unspecified.
1028 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1029 TTP->getPosition()))
1032 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1034 if (TTP->isParameterPack()) {
1035 assert(Arg.getKind() == TemplateArgument::Pack &&
1036 "Missing argument pack");
1038 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1039 // We have the template argument pack to substitute, but we're not
1040 // actually expanding the enclosing pack expansion yet. So, just
1041 // keep the entire argument pack.
1042 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1045 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1048 TemplateName Template = Arg.getAsTemplate();
1049 assert(!Template.isNull() && "Null template template argument");
1051 // We don't ever want to substitute for a qualified template name, since
1052 // the qualifier is handled separately. So, look through the qualified
1053 // template name to its underlying declaration.
1054 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1055 Template = TemplateName(QTN->getTemplateDecl());
1057 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1062 if (SubstTemplateTemplateParmPackStorage *SubstPack
1063 = Name.getAsSubstTemplateTemplateParmPack()) {
1064 if (getSema().ArgumentPackSubstitutionIndex == -1)
1067 TemplateArgument Arg = SubstPack->getArgumentPack();
1068 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1069 return Arg.getAsTemplate();
1072 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1073 FirstQualifierInScope);
1077 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1078 if (!E->isTypeDependent())
1081 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1085 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1086 NonTypeTemplateParmDecl *NTTP) {
1087 // If the corresponding template argument is NULL or non-existent, it's
1088 // because we are performing instantiation from explicitly-specified
1089 // template arguments in a function template, but there were some
1090 // arguments left unspecified.
1091 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1092 NTTP->getPosition()))
1095 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1096 if (NTTP->isParameterPack()) {
1097 assert(Arg.getKind() == TemplateArgument::Pack &&
1098 "Missing argument pack");
1100 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1101 // We have an argument pack, but we can't select a particular argument
1102 // out of it yet. Therefore, we'll build an expression to hold on to that
1104 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1106 NTTP->getDeclName());
1107 if (TargetType.isNull())
1110 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1116 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1119 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1122 const LoopHintAttr *
1123 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1124 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1126 if (TransformedExpr == LH->getValue())
1129 // Generate error if there is a problem with the value.
1130 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1133 // Create new LoopHintValueAttr with integral expression in place of the
1134 // non-type template parameter.
1135 return LoopHintAttr::CreateImplicit(
1136 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1137 LH->getState(), TransformedExpr, LH->getRange());
1140 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1141 NonTypeTemplateParmDecl *parm,
1143 TemplateArgument arg) {
1147 // The template argument itself might be an expression, in which
1148 // case we just return that expression.
1149 if (arg.getKind() == TemplateArgument::Expression) {
1150 Expr *argExpr = arg.getAsExpr();
1152 type = argExpr->getType();
1154 } else if (arg.getKind() == TemplateArgument::Declaration ||
1155 arg.getKind() == TemplateArgument::NullPtr) {
1157 if (arg.getKind() == TemplateArgument::Declaration) {
1158 VD = cast<ValueDecl>(arg.getAsDecl());
1160 // Find the instantiation of the template argument. This is
1161 // required for nested templates.
1162 VD = cast_or_null<ValueDecl>(
1163 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1167 // Propagate NULL template argument.
1171 // Derive the type we want the substituted decl to have. This had
1172 // better be non-dependent, or these checks will have serious problems.
1173 if (parm->isExpandedParameterPack()) {
1174 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1175 } else if (parm->isParameterPack() &&
1176 isa<PackExpansionType>(parm->getType())) {
1177 type = SemaRef.SubstType(
1178 cast<PackExpansionType>(parm->getType())->getPattern(),
1179 TemplateArgs, loc, parm->getDeclName());
1181 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1182 loc, parm->getDeclName());
1184 assert(!type.isNull() && "type substitution failed for param type");
1185 assert(!type->isDependentType() && "param type still dependent");
1186 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1188 if (!result.isInvalid()) type = result.get()->getType();
1190 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1192 // Note that this type can be different from the type of 'result',
1193 // e.g. if it's an enum type.
1194 type = arg.getIntegralType();
1196 if (result.isInvalid()) return ExprError();
1198 Expr *resultExpr = result.get();
1199 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1200 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1204 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1205 SubstNonTypeTemplateParmPackExpr *E) {
1206 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1207 // We aren't expanding the parameter pack, so just return ourselves.
1211 TemplateArgument Arg = E->getArgumentPack();
1212 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1213 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1214 E->getParameterPackLocation(),
1219 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1220 SourceLocation Loc) {
1221 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1222 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1226 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1227 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1228 // We can expand this parameter pack now.
1229 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1230 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1233 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1236 QualType T = TransformType(E->getType());
1240 // Transform each of the parameter expansions into the corresponding
1241 // parameters in the instantiation of the function decl.
1242 SmallVector<ParmVarDecl *, 8> Parms;
1243 Parms.reserve(E->getNumExpansions());
1244 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1247 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1253 return FunctionParmPackExpr::Create(getSema().Context, T,
1254 E->getParameterPack(),
1255 E->getParameterPackLocation(), Parms);
1259 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1261 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1262 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1263 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1264 assert(Found && "no instantiation for parameter pack");
1266 Decl *TransformedDecl;
1267 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1268 // If this is a reference to a function parameter pack which we can
1269 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1270 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1271 QualType T = TransformType(E->getType());
1274 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1275 E->getExprLoc(), *Pack);
1278 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1280 TransformedDecl = Found->get<Decl*>();
1283 // We have either an unexpanded pack or a specific expansion.
1284 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1289 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1290 NamedDecl *D = E->getDecl();
1292 // Handle references to non-type template parameters and non-type template
1294 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1295 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1296 return TransformTemplateParmRefExpr(E, NTTP);
1298 // We have a non-type template parameter that isn't fully substituted;
1299 // FindInstantiatedDecl will find it in the local instantiation scope.
1302 // Handle references to function parameter packs.
1303 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1304 if (PD->isParameterPack())
1305 return TransformFunctionParmPackRefExpr(E, PD);
1307 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1310 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1311 CXXDefaultArgExpr *E) {
1312 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1313 getDescribedFunctionTemplate() &&
1314 "Default arg expressions are never formed in dependent cases.");
1315 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1316 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1320 template<typename Fn>
1321 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1322 FunctionProtoTypeLoc TL,
1323 CXXRecordDecl *ThisContext,
1324 unsigned ThisTypeQuals,
1325 Fn TransformExceptionSpec) {
1326 // We need a local instantiation scope for this function prototype.
1327 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1328 return inherited::TransformFunctionProtoType(
1329 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1333 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1334 int indexAdjustment,
1335 Optional<unsigned> NumExpansions,
1336 bool ExpectParameterPack) {
1337 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1338 NumExpansions, ExpectParameterPack);
1342 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1343 TemplateTypeParmTypeLoc TL) {
1344 const TemplateTypeParmType *T = TL.getTypePtr();
1345 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1346 // Replace the template type parameter with its corresponding
1347 // template argument.
1349 // If the corresponding template argument is NULL or doesn't exist, it's
1350 // because we are performing instantiation from explicitly-specified
1351 // template arguments in a function template class, but there were some
1352 // arguments left unspecified.
1353 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1354 TemplateTypeParmTypeLoc NewTL
1355 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1356 NewTL.setNameLoc(TL.getNameLoc());
1357 return TL.getType();
1360 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1362 if (T->isParameterPack()) {
1363 assert(Arg.getKind() == TemplateArgument::Pack &&
1364 "Missing argument pack");
1366 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1367 // We have the template argument pack, but we're not expanding the
1368 // enclosing pack expansion yet. Just save the template argument
1369 // pack for later substitution.
1371 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1372 SubstTemplateTypeParmPackTypeLoc NewTL
1373 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1374 NewTL.setNameLoc(TL.getNameLoc());
1378 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1381 assert(Arg.getKind() == TemplateArgument::Type &&
1382 "Template argument kind mismatch");
1384 QualType Replacement = Arg.getAsType();
1386 // TODO: only do this uniquing once, at the start of instantiation.
1388 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1389 SubstTemplateTypeParmTypeLoc NewTL
1390 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1391 NewTL.setNameLoc(TL.getNameLoc());
1395 // The template type parameter comes from an inner template (e.g.,
1396 // the template parameter list of a member template inside the
1397 // template we are instantiating). Create a new template type
1398 // parameter with the template "level" reduced by one.
1399 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1400 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1401 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1402 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1405 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1406 - TemplateArgs.getNumLevels(),
1408 T->isParameterPack(),
1410 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1411 NewTL.setNameLoc(TL.getNameLoc());
1416 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1417 TypeLocBuilder &TLB,
1418 SubstTemplateTypeParmPackTypeLoc TL) {
1419 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1420 // We aren't expanding the parameter pack, so just return ourselves.
1421 SubstTemplateTypeParmPackTypeLoc NewTL
1422 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1423 NewTL.setNameLoc(TL.getNameLoc());
1424 return TL.getType();
1427 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1428 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1429 QualType Result = Arg.getAsType();
1431 Result = getSema().Context.getSubstTemplateTypeParmType(
1432 TL.getTypePtr()->getReplacedParameter(),
1434 SubstTemplateTypeParmTypeLoc NewTL
1435 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1436 NewTL.setNameLoc(TL.getNameLoc());
1440 /// \brief Perform substitution on the type T with a given set of template
1443 /// This routine substitutes the given template arguments into the
1444 /// type T and produces the instantiated type.
1446 /// \param T the type into which the template arguments will be
1447 /// substituted. If this type is not dependent, it will be returned
1450 /// \param Args the template arguments that will be
1451 /// substituted for the top-level template parameters within T.
1453 /// \param Loc the location in the source code where this substitution
1454 /// is being performed. It will typically be the location of the
1455 /// declarator (if we're instantiating the type of some declaration)
1456 /// or the location of the type in the source code (if, e.g., we're
1457 /// instantiating the type of a cast expression).
1459 /// \param Entity the name of the entity associated with a declaration
1460 /// being instantiated (if any). May be empty to indicate that there
1461 /// is no such entity (if, e.g., this is a type that occurs as part of
1462 /// a cast expression) or that the entity has no name (e.g., an
1463 /// unnamed function parameter).
1465 /// \returns If the instantiation succeeds, the instantiated
1466 /// type. Otherwise, produces diagnostics and returns a NULL type.
1467 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1468 const MultiLevelTemplateArgumentList &Args,
1470 DeclarationName Entity) {
1471 assert(!ActiveTemplateInstantiations.empty() &&
1472 "Cannot perform an instantiation without some context on the "
1473 "instantiation stack");
1475 if (!T->getType()->isInstantiationDependentType() &&
1476 !T->getType()->isVariablyModifiedType())
1479 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1480 return Instantiator.TransformType(T);
1483 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1484 const MultiLevelTemplateArgumentList &Args,
1486 DeclarationName Entity) {
1487 assert(!ActiveTemplateInstantiations.empty() &&
1488 "Cannot perform an instantiation without some context on the "
1489 "instantiation stack");
1491 if (TL.getType().isNull())
1494 if (!TL.getType()->isInstantiationDependentType() &&
1495 !TL.getType()->isVariablyModifiedType()) {
1496 // FIXME: Make a copy of the TypeLoc data here, so that we can
1497 // return a new TypeSourceInfo. Inefficient!
1499 TLB.pushFullCopy(TL);
1500 return TLB.getTypeSourceInfo(Context, TL.getType());
1503 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1505 TLB.reserve(TL.getFullDataSize());
1506 QualType Result = Instantiator.TransformType(TLB, TL);
1507 if (Result.isNull())
1510 return TLB.getTypeSourceInfo(Context, Result);
1513 /// Deprecated form of the above.
1514 QualType Sema::SubstType(QualType T,
1515 const MultiLevelTemplateArgumentList &TemplateArgs,
1516 SourceLocation Loc, DeclarationName Entity) {
1517 assert(!ActiveTemplateInstantiations.empty() &&
1518 "Cannot perform an instantiation without some context on the "
1519 "instantiation stack");
1521 // If T is not a dependent type or a variably-modified type, there
1522 // is nothing to do.
1523 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1526 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1527 return Instantiator.TransformType(T);
1530 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1531 if (T->getType()->isInstantiationDependentType() ||
1532 T->getType()->isVariablyModifiedType())
1535 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1536 if (!TL.getAs<FunctionProtoTypeLoc>())
1539 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1540 for (ParmVarDecl *P : FP.getParams()) {
1541 // This must be synthesized from a typedef.
1544 // If there are any parameters, a new TypeSourceInfo that refers to the
1545 // instantiated parameters must be built.
1552 /// A form of SubstType intended specifically for instantiating the
1553 /// type of a FunctionDecl. Its purpose is solely to force the
1554 /// instantiation of default-argument expressions and to avoid
1555 /// instantiating an exception-specification.
1556 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1557 const MultiLevelTemplateArgumentList &Args,
1559 DeclarationName Entity,
1560 CXXRecordDecl *ThisContext,
1561 unsigned ThisTypeQuals) {
1562 assert(!ActiveTemplateInstantiations.empty() &&
1563 "Cannot perform an instantiation without some context on the "
1564 "instantiation stack");
1566 if (!NeedsInstantiationAsFunctionType(T))
1569 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1573 TypeLoc TL = T->getTypeLoc();
1574 TLB.reserve(TL.getFullDataSize());
1578 if (FunctionProtoTypeLoc Proto =
1579 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1580 // Instantiate the type, other than its exception specification. The
1581 // exception specification is instantiated in InitFunctionInstantiation
1582 // once we've built the FunctionDecl.
1583 // FIXME: Set the exception specification to EST_Uninstantiated here,
1584 // instead of rebuilding the function type again later.
1585 Result = Instantiator.TransformFunctionProtoType(
1586 TLB, Proto, ThisContext, ThisTypeQuals,
1587 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1588 bool &Changed) { return false; });
1590 Result = Instantiator.TransformType(TLB, TL);
1592 if (Result.isNull())
1595 return TLB.getTypeSourceInfo(Context, Result);
1598 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1599 const MultiLevelTemplateArgumentList &Args) {
1600 FunctionProtoType::ExceptionSpecInfo ESI =
1601 Proto->getExtProtoInfo().ExceptionSpec;
1602 assert(ESI.Type != EST_Uninstantiated);
1604 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1605 New->getDeclName());
1607 SmallVector<QualType, 4> ExceptionStorage;
1608 bool Changed = false;
1609 if (Instantiator.TransformExceptionSpec(
1610 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1611 ExceptionStorage, Changed))
1612 // On error, recover by dropping the exception specification.
1613 ESI.Type = EST_None;
1615 UpdateExceptionSpec(New, ESI);
1618 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1619 const MultiLevelTemplateArgumentList &TemplateArgs,
1620 int indexAdjustment,
1621 Optional<unsigned> NumExpansions,
1622 bool ExpectParameterPack) {
1623 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1624 TypeSourceInfo *NewDI = nullptr;
1626 TypeLoc OldTL = OldDI->getTypeLoc();
1627 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1629 // We have a function parameter pack. Substitute into the pattern of the
1631 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1632 OldParm->getLocation(), OldParm->getDeclName());
1636 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1637 // We still have unexpanded parameter packs, which means that
1638 // our function parameter is still a function parameter pack.
1639 // Therefore, make its type a pack expansion type.
1640 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1642 } else if (ExpectParameterPack) {
1643 // We expected to get a parameter pack but didn't (because the type
1644 // itself is not a pack expansion type), so complain. This can occur when
1645 // the substitution goes through an alias template that "loses" the
1647 Diag(OldParm->getLocation(),
1648 diag::err_function_parameter_pack_without_parameter_packs)
1649 << NewDI->getType();
1653 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1654 OldParm->getDeclName());
1660 if (NewDI->getType()->isVoidType()) {
1661 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1665 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1666 OldParm->getInnerLocStart(),
1667 OldParm->getLocation(),
1668 OldParm->getIdentifier(),
1669 NewDI->getType(), NewDI,
1670 OldParm->getStorageClass());
1674 // Mark the (new) default argument as uninstantiated (if any).
1675 if (OldParm->hasUninstantiatedDefaultArg()) {
1676 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1677 NewParm->setUninstantiatedDefaultArg(Arg);
1678 } else if (OldParm->hasUnparsedDefaultArg()) {
1679 NewParm->setUnparsedDefaultArg();
1680 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1681 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1682 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1683 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1684 // Instantiate default arguments for methods of local classes (DR1484)
1685 // and non-defining declarations.
1686 Sema::ContextRAII SavedContext(*this, OwningFunc);
1687 LocalInstantiationScope Local(*this);
1688 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1689 if (NewArg.isUsable()) {
1690 // It would be nice if we still had this.
1691 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1692 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1695 // FIXME: if we non-lazily instantiated non-dependent default args for
1696 // non-dependent parameter types we could remove a bunch of duplicate
1697 // conversion warnings for such arguments.
1698 NewParm->setUninstantiatedDefaultArg(Arg);
1702 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1704 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1705 // Add the new parameter to the instantiated parameter pack.
1706 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1708 // Introduce an Old -> New mapping
1709 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1712 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1713 // can be anything, is this right ?
1714 NewParm->setDeclContext(CurContext);
1716 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1717 OldParm->getFunctionScopeIndex() + indexAdjustment);
1719 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1724 /// \brief Substitute the given template arguments into the given set of
1725 /// parameters, producing the set of parameter types that would be generated
1726 /// from such a substitution.
1727 bool Sema::SubstParmTypes(
1728 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1729 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1730 const MultiLevelTemplateArgumentList &TemplateArgs,
1731 SmallVectorImpl<QualType> &ParamTypes,
1732 SmallVectorImpl<ParmVarDecl *> *OutParams,
1733 ExtParameterInfoBuilder &ParamInfos) {
1734 assert(!ActiveTemplateInstantiations.empty() &&
1735 "Cannot perform an instantiation without some context on the "
1736 "instantiation stack");
1738 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1740 return Instantiator.TransformFunctionTypeParams(
1741 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1744 /// \brief Perform substitution on the base class specifiers of the
1745 /// given class template specialization.
1747 /// Produces a diagnostic and returns true on error, returns false and
1748 /// attaches the instantiated base classes to the class template
1749 /// specialization if successful.
1751 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1752 CXXRecordDecl *Pattern,
1753 const MultiLevelTemplateArgumentList &TemplateArgs) {
1754 bool Invalid = false;
1755 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1756 for (const auto &Base : Pattern->bases()) {
1757 if (!Base.getType()->isDependentType()) {
1758 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1759 if (RD->isInvalidDecl())
1760 Instantiation->setInvalidDecl();
1762 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1766 SourceLocation EllipsisLoc;
1767 TypeSourceInfo *BaseTypeLoc;
1768 if (Base.isPackExpansion()) {
1769 // This is a pack expansion. See whether we should expand it now, or
1770 // wait until later.
1771 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1772 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1774 bool ShouldExpand = false;
1775 bool RetainExpansion = false;
1776 Optional<unsigned> NumExpansions;
1777 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1778 Base.getSourceRange(),
1780 TemplateArgs, ShouldExpand,
1787 // If we should expand this pack expansion now, do so.
1789 for (unsigned I = 0; I != *NumExpansions; ++I) {
1790 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1792 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1794 Base.getSourceRange().getBegin(),
1801 if (CXXBaseSpecifier *InstantiatedBase
1802 = CheckBaseSpecifier(Instantiation,
1803 Base.getSourceRange(),
1805 Base.getAccessSpecifierAsWritten(),
1808 InstantiatedBases.push_back(InstantiatedBase);
1816 // The resulting base specifier will (still) be a pack expansion.
1817 EllipsisLoc = Base.getEllipsisLoc();
1818 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1819 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1821 Base.getSourceRange().getBegin(),
1824 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1826 Base.getSourceRange().getBegin(),
1835 if (CXXBaseSpecifier *InstantiatedBase
1836 = CheckBaseSpecifier(Instantiation,
1837 Base.getSourceRange(),
1839 Base.getAccessSpecifierAsWritten(),
1842 InstantiatedBases.push_back(InstantiatedBase);
1847 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1853 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1856 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1857 const MultiLevelTemplateArgumentList &TemplateArgs);
1861 /// Determine whether we would be unable to instantiate this template (because
1862 /// it either has no definition, or is in the process of being instantiated).
1863 static bool DiagnoseUninstantiableTemplate(Sema &S,
1864 SourceLocation PointOfInstantiation,
1865 TagDecl *Instantiation,
1866 bool InstantiatedFromMember,
1868 TagDecl *PatternDef,
1869 TemplateSpecializationKind TSK,
1870 bool Complain = true) {
1871 if (PatternDef && !PatternDef->isBeingDefined()) {
1872 NamedDecl *SuggestedDef = nullptr;
1873 if (!S.hasVisibleDefinition(PatternDef, &SuggestedDef,
1874 /*OnlyNeedComplete*/false)) {
1875 // If we're allowed to diagnose this and recover, do so.
1876 bool Recover = Complain && !S.isSFINAEContext();
1878 S.diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
1879 Sema::MissingImportKind::Definition, Recover);
1885 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1887 } else if (PatternDef) {
1888 assert(PatternDef->isBeingDefined());
1889 S.Diag(PointOfInstantiation,
1890 diag::err_template_instantiate_within_definition)
1891 << (TSK != TSK_ImplicitInstantiation)
1892 << S.Context.getTypeDeclType(Instantiation);
1893 // Not much point in noting the template declaration here, since
1894 // we're lexically inside it.
1895 Instantiation->setInvalidDecl();
1896 } else if (InstantiatedFromMember) {
1897 S.Diag(PointOfInstantiation,
1898 diag::err_implicit_instantiate_member_undefined)
1899 << S.Context.getTypeDeclType(Instantiation);
1900 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
1902 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1903 << (TSK != TSK_ImplicitInstantiation)
1904 << S.Context.getTypeDeclType(Instantiation);
1905 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1908 // In general, Instantiation isn't marked invalid to get more than one
1909 // error for multiple undefined instantiations. But the code that does
1910 // explicit declaration -> explicit definition conversion can't handle
1911 // invalid declarations, so mark as invalid in that case.
1912 if (TSK == TSK_ExplicitInstantiationDeclaration)
1913 Instantiation->setInvalidDecl();
1917 /// \brief Instantiate the definition of a class from a given pattern.
1919 /// \param PointOfInstantiation The point of instantiation within the
1922 /// \param Instantiation is the declaration whose definition is being
1923 /// instantiated. This will be either a class template specialization
1924 /// or a member class of a class template specialization.
1926 /// \param Pattern is the pattern from which the instantiation
1927 /// occurs. This will be either the declaration of a class template or
1928 /// the declaration of a member class of a class template.
1930 /// \param TemplateArgs The template arguments to be substituted into
1933 /// \param TSK the kind of implicit or explicit instantiation to perform.
1935 /// \param Complain whether to complain if the class cannot be instantiated due
1936 /// to the lack of a definition.
1938 /// \returns true if an error occurred, false otherwise.
1940 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1941 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1942 const MultiLevelTemplateArgumentList &TemplateArgs,
1943 TemplateSpecializationKind TSK,
1945 CXXRecordDecl *PatternDef
1946 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1947 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1948 Instantiation->getInstantiatedFromMemberClass(),
1949 Pattern, PatternDef, TSK, Complain))
1951 Pattern = PatternDef;
1953 // \brief Record the point of instantiation.
1954 if (MemberSpecializationInfo *MSInfo
1955 = Instantiation->getMemberSpecializationInfo()) {
1956 MSInfo->setTemplateSpecializationKind(TSK);
1957 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1958 } else if (ClassTemplateSpecializationDecl *Spec
1959 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1960 Spec->setTemplateSpecializationKind(TSK);
1961 Spec->setPointOfInstantiation(PointOfInstantiation);
1964 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1965 if (Inst.isInvalid())
1967 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
1968 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1969 "instantiating class definition");
1971 // Enter the scope of this instantiation. We don't use
1972 // PushDeclContext because we don't have a scope.
1973 ContextRAII SavedContext(*this, Instantiation);
1974 EnterExpressionEvaluationContext EvalContext(*this,
1975 Sema::PotentiallyEvaluated);
1977 // If this is an instantiation of a local class, merge this local
1978 // instantiation scope with the enclosing scope. Otherwise, every
1979 // instantiation of a class has its own local instantiation scope.
1980 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1981 LocalInstantiationScope Scope(*this, MergeWithParentScope);
1983 // All dllexported classes created during instantiation should be fully
1984 // emitted after instantiation completes. We may not be ready to emit any
1985 // delayed classes already on the stack, so save them away and put them back
1987 decltype(DelayedDllExportClasses) ExportedClasses;
1988 std::swap(ExportedClasses, DelayedDllExportClasses);
1990 // Pull attributes from the pattern onto the instantiation.
1991 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1993 // Start the definition of this instantiation.
1994 Instantiation->startDefinition();
1996 // The instantiation is visible here, even if it was first declared in an
1997 // unimported module.
1998 Instantiation->setHidden(false);
2000 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2001 Instantiation->setTagKind(Pattern->getTagKind());
2003 // Do substitution on the base class specifiers.
2004 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2005 Instantiation->setInvalidDecl();
2007 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2008 SmallVector<Decl*, 4> Fields;
2009 // Delay instantiation of late parsed attributes.
2010 LateInstantiatedAttrVec LateAttrs;
2011 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2013 for (auto *Member : Pattern->decls()) {
2014 // Don't instantiate members not belonging in this semantic context.
2017 // template <int i> class A {
2021 // 'class B' has the template as lexical context but semantically it is
2022 // introduced in namespace scope.
2023 if (Member->getDeclContext() != Pattern)
2026 if (Member->isInvalidDecl()) {
2027 Instantiation->setInvalidDecl();
2031 Decl *NewMember = Instantiator.Visit(Member);
2033 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2034 Fields.push_back(Field);
2035 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2036 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2037 // specialization causes the implicit instantiation of the definitions
2038 // of unscoped member enumerations.
2039 // Record a point of instantiation for this implicit instantiation.
2040 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2041 Enum->isCompleteDefinition()) {
2042 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2043 assert(MSInfo && "no spec info for member enum specialization");
2044 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2045 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2047 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2048 if (SA->isFailed()) {
2049 // A static_assert failed. Bail out; instantiating this
2050 // class is probably not meaningful.
2051 Instantiation->setInvalidDecl();
2056 if (NewMember->isInvalidDecl())
2057 Instantiation->setInvalidDecl();
2059 // FIXME: Eventually, a NULL return will mean that one of the
2060 // instantiations was a semantic disaster, and we'll want to mark the
2061 // declaration invalid.
2062 // For now, we expect to skip some members that we can't yet handle.
2066 // Finish checking fields.
2067 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2068 SourceLocation(), SourceLocation(), nullptr);
2069 CheckCompletedCXXClass(Instantiation);
2071 // Default arguments are parsed, if not instantiated. We can go instantiate
2072 // default arg exprs for default constructors if necessary now.
2073 ActOnFinishCXXNonNestedClass(Instantiation);
2075 // Put back the delayed exported classes that we moved out of the way.
2076 std::swap(ExportedClasses, DelayedDllExportClasses);
2078 // Instantiate late parsed attributes, and attach them to their decls.
2079 // See Sema::InstantiateAttrs
2080 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2081 E = LateAttrs.end(); I != E; ++I) {
2082 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2083 CurrentInstantiationScope = I->Scope;
2085 // Allow 'this' within late-parsed attributes.
2086 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2087 CXXRecordDecl *ThisContext =
2088 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2089 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2090 ND && ND->isCXXInstanceMember());
2093 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2094 I->NewDecl->addAttr(NewAttr);
2095 LocalInstantiationScope::deleteScopes(I->Scope,
2096 Instantiator.getStartingScope());
2098 Instantiator.disableLateAttributeInstantiation();
2101 ActOnFinishDelayedMemberInitializers(Instantiation);
2103 // FIXME: We should do something similar for explicit instantiations so they
2104 // end up in the right module.
2105 if (TSK == TSK_ImplicitInstantiation) {
2106 Instantiation->setLocation(Pattern->getLocation());
2107 Instantiation->setLocStart(Pattern->getInnerLocStart());
2108 Instantiation->setBraceRange(Pattern->getBraceRange());
2111 if (!Instantiation->isInvalidDecl()) {
2112 // Perform any dependent diagnostics from the pattern.
2113 PerformDependentDiagnostics(Pattern, TemplateArgs);
2115 // Instantiate any out-of-line class template partial
2116 // specializations now.
2117 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2118 P = Instantiator.delayed_partial_spec_begin(),
2119 PEnd = Instantiator.delayed_partial_spec_end();
2121 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2122 P->first, P->second)) {
2123 Instantiation->setInvalidDecl();
2128 // Instantiate any out-of-line variable template partial
2129 // specializations now.
2130 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2131 P = Instantiator.delayed_var_partial_spec_begin(),
2132 PEnd = Instantiator.delayed_var_partial_spec_end();
2134 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2135 P->first, P->second)) {
2136 Instantiation->setInvalidDecl();
2142 // Exit the scope of this instantiation.
2145 if (!Instantiation->isInvalidDecl()) {
2146 Consumer.HandleTagDeclDefinition(Instantiation);
2148 // Always emit the vtable for an explicit instantiation definition
2149 // of a polymorphic class template specialization.
2150 if (TSK == TSK_ExplicitInstantiationDefinition)
2151 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2154 return Instantiation->isInvalidDecl();
2157 /// \brief Instantiate the definition of an enum from a given pattern.
2159 /// \param PointOfInstantiation The point of instantiation within the
2161 /// \param Instantiation is the declaration whose definition is being
2162 /// instantiated. This will be a member enumeration of a class
2163 /// temploid specialization, or a local enumeration within a
2164 /// function temploid specialization.
2165 /// \param Pattern The templated declaration from which the instantiation
2167 /// \param TemplateArgs The template arguments to be substituted into
2169 /// \param TSK The kind of implicit or explicit instantiation to perform.
2171 /// \return \c true if an error occurred, \c false otherwise.
2172 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2173 EnumDecl *Instantiation, EnumDecl *Pattern,
2174 const MultiLevelTemplateArgumentList &TemplateArgs,
2175 TemplateSpecializationKind TSK) {
2176 EnumDecl *PatternDef = Pattern->getDefinition();
2177 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2178 Instantiation->getInstantiatedFromMemberEnum(),
2179 Pattern, PatternDef, TSK,/*Complain*/true))
2181 Pattern = PatternDef;
2183 // Record the point of instantiation.
2184 if (MemberSpecializationInfo *MSInfo
2185 = Instantiation->getMemberSpecializationInfo()) {
2186 MSInfo->setTemplateSpecializationKind(TSK);
2187 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2190 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2191 if (Inst.isInvalid())
2193 if (Inst.isAlreadyInstantiating())
2195 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2196 "instantiating enum definition");
2198 // The instantiation is visible here, even if it was first declared in an
2199 // unimported module.
2200 Instantiation->setHidden(false);
2202 // Enter the scope of this instantiation. We don't use
2203 // PushDeclContext because we don't have a scope.
2204 ContextRAII SavedContext(*this, Instantiation);
2205 EnterExpressionEvaluationContext EvalContext(*this,
2206 Sema::PotentiallyEvaluated);
2208 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2210 // Pull attributes from the pattern onto the instantiation.
2211 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2213 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2214 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2216 // Exit the scope of this instantiation.
2219 return Instantiation->isInvalidDecl();
2223 /// \brief Instantiate the definition of a field from the given pattern.
2225 /// \param PointOfInstantiation The point of instantiation within the
2227 /// \param Instantiation is the declaration whose definition is being
2228 /// instantiated. This will be a class of a class temploid
2229 /// specialization, or a local enumeration within a function temploid
2231 /// \param Pattern The templated declaration from which the instantiation
2233 /// \param TemplateArgs The template arguments to be substituted into
2236 /// \return \c true if an error occurred, \c false otherwise.
2237 bool Sema::InstantiateInClassInitializer(
2238 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2239 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2240 // If there is no initializer, we don't need to do anything.
2241 if (!Pattern->hasInClassInitializer())
2244 assert(Instantiation->getInClassInitStyle() ==
2245 Pattern->getInClassInitStyle() &&
2246 "pattern and instantiation disagree about init style");
2248 // Error out if we haven't parsed the initializer of the pattern yet because
2249 // we are waiting for the closing brace of the outer class.
2250 Expr *OldInit = Pattern->getInClassInitializer();
2252 RecordDecl *PatternRD = Pattern->getParent();
2253 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2254 if (OutermostClass == PatternRD) {
2255 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2256 << PatternRD << Pattern;
2258 Diag(Pattern->getLocEnd(),
2259 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2260 << PatternRD << OutermostClass << Pattern;
2262 Instantiation->setInvalidDecl();
2266 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2267 if (Inst.isInvalid())
2269 if (Inst.isAlreadyInstantiating()) {
2270 // Error out if we hit an instantiation cycle for this initializer.
2271 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2275 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2276 "instantiating default member init");
2278 // Enter the scope of this instantiation. We don't use PushDeclContext because
2279 // we don't have a scope.
2280 ContextRAII SavedContext(*this, Instantiation->getParent());
2281 EnterExpressionEvaluationContext EvalContext(*this,
2282 Sema::PotentiallyEvaluated);
2284 LocalInstantiationScope Scope(*this, true);
2286 // Instantiate the initializer.
2287 ActOnStartCXXInClassMemberInitializer();
2288 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2290 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2291 /*CXXDirectInit=*/false);
2292 Expr *Init = NewInit.get();
2293 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2294 ActOnFinishCXXInClassMemberInitializer(
2295 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2297 // Exit the scope of this instantiation.
2300 // Return true if the in-class initializer is still missing.
2301 return !Instantiation->getInClassInitializer();
2305 /// \brief A partial specialization whose template arguments have matched
2306 /// a given template-id.
2307 struct PartialSpecMatchResult {
2308 ClassTemplatePartialSpecializationDecl *Partial;
2309 TemplateArgumentList *Args;
2313 bool Sema::InstantiateClassTemplateSpecialization(
2314 SourceLocation PointOfInstantiation,
2315 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2316 TemplateSpecializationKind TSK, bool Complain) {
2317 // Perform the actual instantiation on the canonical declaration.
2318 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2319 ClassTemplateSpec->getCanonicalDecl());
2320 if (ClassTemplateSpec->isInvalidDecl())
2323 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2324 CXXRecordDecl *Pattern = nullptr;
2326 // C++ [temp.class.spec.match]p1:
2327 // When a class template is used in a context that requires an
2328 // instantiation of the class, it is necessary to determine
2329 // whether the instantiation is to be generated using the primary
2330 // template or one of the partial specializations. This is done by
2331 // matching the template arguments of the class template
2332 // specialization with the template argument lists of the partial
2334 typedef PartialSpecMatchResult MatchResult;
2335 SmallVector<MatchResult, 4> Matched;
2336 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2337 Template->getPartialSpecializations(PartialSpecs);
2338 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2339 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2340 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2341 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2342 if (TemplateDeductionResult Result
2343 = DeduceTemplateArguments(Partial,
2344 ClassTemplateSpec->getTemplateArgs(),
2346 // Store the failed-deduction information for use in diagnostics, later.
2347 // TODO: Actually use the failed-deduction info?
2348 FailedCandidates.addCandidate().set(
2349 DeclAccessPair::make(Template, AS_public), Partial,
2350 MakeDeductionFailureInfo(Context, Result, Info));
2353 Matched.push_back(PartialSpecMatchResult());
2354 Matched.back().Partial = Partial;
2355 Matched.back().Args = Info.take();
2359 // If we're dealing with a member template where the template parameters
2360 // have been instantiated, this provides the original template parameters
2361 // from which the member template's parameters were instantiated.
2363 if (Matched.size() >= 1) {
2364 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2365 if (Matched.size() == 1) {
2366 // -- If exactly one matching specialization is found, the
2367 // instantiation is generated from that specialization.
2368 // We don't need to do anything for this.
2370 // -- If more than one matching specialization is found, the
2371 // partial order rules (14.5.4.2) are used to determine
2372 // whether one of the specializations is more specialized
2373 // than the others. If none of the specializations is more
2374 // specialized than all of the other matching
2375 // specializations, then the use of the class template is
2376 // ambiguous and the program is ill-formed.
2377 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2378 PEnd = Matched.end();
2380 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2381 PointOfInstantiation)
2386 // Determine if the best partial specialization is more specialized than
2388 bool Ambiguous = false;
2389 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2390 PEnd = Matched.end();
2393 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2394 PointOfInstantiation)
2402 // Partial ordering did not produce a clear winner. Complain.
2403 ClassTemplateSpec->setInvalidDecl();
2404 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2405 << ClassTemplateSpec;
2407 // Print the matching partial specializations.
2408 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2409 PEnd = Matched.end();
2411 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2412 << getTemplateArgumentBindingsText(
2413 P->Partial->getTemplateParameters(),
2420 // Instantiate using the best class template partial specialization.
2421 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2422 while (OrigPartialSpec->getInstantiatedFromMember()) {
2423 // If we've found an explicit specialization of this class template,
2424 // stop here and use that as the pattern.
2425 if (OrigPartialSpec->isMemberSpecialization())
2428 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2431 Pattern = OrigPartialSpec;
2432 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2434 // -- If no matches are found, the instantiation is generated
2435 // from the primary template.
2436 ClassTemplateDecl *OrigTemplate = Template;
2437 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2438 // If we've found an explicit specialization of this class template,
2439 // stop here and use that as the pattern.
2440 if (OrigTemplate->isMemberSpecialization())
2443 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2446 Pattern = OrigTemplate->getTemplatedDecl();
2449 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2451 getTemplateInstantiationArgs(ClassTemplateSpec),
2458 /// \brief Instantiates the definitions of all of the member
2459 /// of the given class, which is an instantiation of a class template
2460 /// or a member class of a template.
2462 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2463 CXXRecordDecl *Instantiation,
2464 const MultiLevelTemplateArgumentList &TemplateArgs,
2465 TemplateSpecializationKind TSK) {
2466 // FIXME: We need to notify the ASTMutationListener that we did all of these
2467 // things, in case we have an explicit instantiation definition in a PCM, a
2468 // module, or preamble, and the declaration is in an imported AST.
2470 (TSK == TSK_ExplicitInstantiationDefinition ||
2471 TSK == TSK_ExplicitInstantiationDeclaration ||
2472 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2473 "Unexpected template specialization kind!");
2474 for (auto *D : Instantiation->decls()) {
2475 bool SuppressNew = false;
2476 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2477 if (FunctionDecl *Pattern
2478 = Function->getInstantiatedFromMemberFunction()) {
2479 MemberSpecializationInfo *MSInfo
2480 = Function->getMemberSpecializationInfo();
2481 assert(MSInfo && "No member specialization information?");
2482 if (MSInfo->getTemplateSpecializationKind()
2483 == TSK_ExplicitSpecialization)
2486 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2488 MSInfo->getTemplateSpecializationKind(),
2489 MSInfo->getPointOfInstantiation(),
2494 // C++11 [temp.explicit]p8:
2495 // An explicit instantiation definition that names a class template
2496 // specialization explicitly instantiates the class template
2497 // specialization and is only an explicit instantiation definition
2498 // of members whose definition is visible at the point of
2500 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2503 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2505 if (Function->isDefined()) {
2506 // Let the ASTConsumer know that this function has been explicitly
2507 // instantiated now, and its linkage might have changed.
2508 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2509 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2510 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2511 } else if (TSK == TSK_ImplicitInstantiation) {
2512 PendingLocalImplicitInstantiations.push_back(
2513 std::make_pair(Function, PointOfInstantiation));
2516 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2517 if (isa<VarTemplateSpecializationDecl>(Var))
2520 if (Var->isStaticDataMember()) {
2521 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2522 assert(MSInfo && "No member specialization information?");
2523 if (MSInfo->getTemplateSpecializationKind()
2524 == TSK_ExplicitSpecialization)
2527 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2529 MSInfo->getTemplateSpecializationKind(),
2530 MSInfo->getPointOfInstantiation(),
2535 if (TSK == TSK_ExplicitInstantiationDefinition) {
2536 // C++0x [temp.explicit]p8:
2537 // An explicit instantiation definition that names a class template
2538 // specialization explicitly instantiates the class template
2539 // specialization and is only an explicit instantiation definition
2540 // of members whose definition is visible at the point of
2542 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2545 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2546 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2548 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2551 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2552 // Always skip the injected-class-name, along with any
2553 // redeclarations of nested classes, since both would cause us
2554 // to try to instantiate the members of a class twice.
2555 // Skip closure types; they'll get instantiated when we instantiate
2556 // the corresponding lambda-expression.
2557 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2561 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2562 assert(MSInfo && "No member specialization information?");
2564 if (MSInfo->getTemplateSpecializationKind()
2565 == TSK_ExplicitSpecialization)
2568 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2569 TSK == TSK_ExplicitInstantiationDeclaration) {
2570 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2571 // affect the inner class.
2575 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2577 MSInfo->getTemplateSpecializationKind(),
2578 MSInfo->getPointOfInstantiation(),
2583 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2584 assert(Pattern && "Missing instantiated-from-template information");
2586 if (!Record->getDefinition()) {
2587 if (!Pattern->getDefinition()) {
2588 // C++0x [temp.explicit]p8:
2589 // An explicit instantiation definition that names a class template
2590 // specialization explicitly instantiates the class template
2591 // specialization and is only an explicit instantiation definition
2592 // of members whose definition is visible at the point of
2594 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2595 MSInfo->setTemplateSpecializationKind(TSK);
2596 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2602 InstantiateClass(PointOfInstantiation, Record, Pattern,
2606 if (TSK == TSK_ExplicitInstantiationDefinition &&
2607 Record->getTemplateSpecializationKind() ==
2608 TSK_ExplicitInstantiationDeclaration) {
2609 Record->setTemplateSpecializationKind(TSK);
2610 MarkVTableUsed(PointOfInstantiation, Record, true);
2614 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2616 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2618 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2619 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2620 assert(MSInfo && "No member specialization information?");
2622 if (MSInfo->getTemplateSpecializationKind()
2623 == TSK_ExplicitSpecialization)
2626 if (CheckSpecializationInstantiationRedecl(
2627 PointOfInstantiation, TSK, Enum,
2628 MSInfo->getTemplateSpecializationKind(),
2629 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2633 if (Enum->getDefinition())
2636 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2637 assert(Pattern && "Missing instantiated-from-template information");
2639 if (TSK == TSK_ExplicitInstantiationDefinition) {
2640 if (!Pattern->getDefinition())
2643 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2645 MSInfo->setTemplateSpecializationKind(TSK);
2646 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2648 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2649 // No need to instantiate in-class initializers during explicit
2651 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2652 CXXRecordDecl *ClassPattern =
2653 Instantiation->getTemplateInstantiationPattern();
2654 DeclContext::lookup_result Lookup =
2655 ClassPattern->lookup(Field->getDeclName());
2656 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2657 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2664 /// \brief Instantiate the definitions of all of the members of the
2665 /// given class template specialization, which was named as part of an
2666 /// explicit instantiation.
2668 Sema::InstantiateClassTemplateSpecializationMembers(
2669 SourceLocation PointOfInstantiation,
2670 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2671 TemplateSpecializationKind TSK) {
2672 // C++0x [temp.explicit]p7:
2673 // An explicit instantiation that names a class template
2674 // specialization is an explicit instantion of the same kind
2675 // (declaration or definition) of each of its members (not
2676 // including members inherited from base classes) that has not
2677 // been previously explicitly specialized in the translation unit
2678 // containing the explicit instantiation, except as described
2680 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2681 getTemplateInstantiationArgs(ClassTemplateSpec),
2686 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2690 TemplateInstantiator Instantiator(*this, TemplateArgs,
2693 return Instantiator.TransformStmt(S);
2697 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2701 TemplateInstantiator Instantiator(*this, TemplateArgs,
2704 return Instantiator.TransformExpr(E);
2707 ExprResult Sema::SubstInitializer(Expr *Init,
2708 const MultiLevelTemplateArgumentList &TemplateArgs,
2709 bool CXXDirectInit) {
2710 TemplateInstantiator Instantiator(*this, TemplateArgs,
2713 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2716 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2717 const MultiLevelTemplateArgumentList &TemplateArgs,
2718 SmallVectorImpl<Expr *> &Outputs) {
2722 TemplateInstantiator Instantiator(*this, TemplateArgs,
2725 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2729 NestedNameSpecifierLoc
2730 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2731 const MultiLevelTemplateArgumentList &TemplateArgs) {
2733 return NestedNameSpecifierLoc();
2735 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2737 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2740 /// \brief Do template substitution on declaration name info.
2742 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2743 const MultiLevelTemplateArgumentList &TemplateArgs) {
2744 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2745 NameInfo.getName());
2746 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2750 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2751 TemplateName Name, SourceLocation Loc,
2752 const MultiLevelTemplateArgumentList &TemplateArgs) {
2753 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2756 SS.Adopt(QualifierLoc);
2757 return Instantiator.TransformTemplateName(SS, Name, Loc);
2760 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2761 TemplateArgumentListInfo &Result,
2762 const MultiLevelTemplateArgumentList &TemplateArgs) {
2763 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2766 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2769 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2770 // When storing ParmVarDecls in the local instantiation scope, we always
2771 // want to use the ParmVarDecl from the canonical function declaration,
2772 // since the map is then valid for any redeclaration or definition of that
2774 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2775 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2776 unsigned i = PV->getFunctionScopeIndex();
2777 // This parameter might be from a freestanding function type within the
2778 // function and isn't necessarily referring to one of FD's parameters.
2779 if (FD->getParamDecl(i) == PV)
2780 return FD->getCanonicalDecl()->getParamDecl(i);
2787 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2788 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2789 D = getCanonicalParmVarDecl(D);
2790 for (LocalInstantiationScope *Current = this; Current;
2791 Current = Current->Outer) {
2793 // Check if we found something within this scope.
2794 const Decl *CheckD = D;
2796 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2797 if (Found != Current->LocalDecls.end())
2798 return &Found->second;
2800 // If this is a tag declaration, it's possible that we need to look for
2801 // a previous declaration.
2802 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2803 CheckD = Tag->getPreviousDecl();
2808 // If we aren't combined with our outer scope, we're done.
2809 if (!Current->CombineWithOuterScope)
2813 // If we're performing a partial substitution during template argument
2814 // deduction, we may not have values for template parameters yet.
2815 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2816 isa<TemplateTemplateParmDecl>(D))
2819 // Local types referenced prior to definition may require instantiation.
2820 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2821 if (RD->isLocalClass())
2824 // Enumeration types referenced prior to definition may appear as a result of
2826 if (isa<EnumDecl>(D))
2829 // If we didn't find the decl, then we either have a sema bug, or we have a
2830 // forward reference to a label declaration. Return null to indicate that
2831 // we have an uninstantiated label.
2832 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2836 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2837 D = getCanonicalParmVarDecl(D);
2838 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2839 if (Stored.isNull()) {
2841 // It should not be present in any surrounding scope either.
2842 LocalInstantiationScope *Current = this;
2843 while (Current->CombineWithOuterScope && Current->Outer) {
2844 Current = Current->Outer;
2845 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2846 "Instantiated local in inner and outer scopes");
2850 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2851 Pack->push_back(cast<ParmVarDecl>(Inst));
2853 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2857 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2858 ParmVarDecl *Inst) {
2859 D = getCanonicalParmVarDecl(D);
2860 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2861 Pack->push_back(Inst);
2864 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2866 // This should be the first time we've been told about this decl.
2867 for (LocalInstantiationScope *Current = this;
2868 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2869 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2870 "Creating local pack after instantiation of local");
2873 D = getCanonicalParmVarDecl(D);
2874 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2875 DeclArgumentPack *Pack = new DeclArgumentPack;
2877 ArgumentPacks.push_back(Pack);
2880 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2881 const TemplateArgument *ExplicitArgs,
2882 unsigned NumExplicitArgs) {
2883 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2884 "Already have a partially-substituted pack");
2885 assert((!PartiallySubstitutedPack
2886 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2887 "Wrong number of arguments in partially-substituted pack");
2888 PartiallySubstitutedPack = Pack;
2889 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2890 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2893 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2894 const TemplateArgument **ExplicitArgs,
2895 unsigned *NumExplicitArgs) const {
2897 *ExplicitArgs = nullptr;
2898 if (NumExplicitArgs)
2899 *NumExplicitArgs = 0;
2901 for (const LocalInstantiationScope *Current = this; Current;
2902 Current = Current->Outer) {
2903 if (Current->PartiallySubstitutedPack) {
2905 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2906 if (NumExplicitArgs)
2907 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2909 return Current->PartiallySubstitutedPack;
2912 if (!Current->CombineWithOuterScope)