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/Sema/DeclSpec.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/Template.h"
19 #include "clang/Sema/TemplateDeduction.h"
20 #include "clang/AST/ASTConsumer.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/Basic/LangOptions.h"
26 using namespace clang;
29 //===----------------------------------------------------------------------===/
30 // Template Instantiation Support
31 //===----------------------------------------------------------------------===/
33 /// \brief Retrieve the template argument list(s) that should be used to
34 /// instantiate the definition of the given declaration.
36 /// \param D the declaration for which we are computing template instantiation
39 /// \param Innermost if non-NULL, the innermost template argument list.
41 /// \param RelativeToPrimary true if we should get the template
42 /// arguments relative to the primary template, even when we're
43 /// dealing with a specialization. This is only relevant for function
44 /// template specializations.
46 /// \param Pattern If non-NULL, indicates the pattern from which we will be
47 /// instantiating the definition of the given declaration, \p D. This is
48 /// used to determine the proper set of template instantiation arguments for
49 /// friend function template specializations.
50 MultiLevelTemplateArgumentList
51 Sema::getTemplateInstantiationArgs(NamedDecl *D,
52 const TemplateArgumentList *Innermost,
53 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
55 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
59 Result.addOuterTemplateArguments(Innermost);
61 DeclContext *Ctx = dyn_cast<DeclContext>(D);
63 Ctx = D->getDeclContext();
65 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
75 Result.addOuterTemplateArguments(0, 0);
81 while (!Ctx->isFileContext()) {
82 // Add template arguments from a class template instantiation.
83 if (ClassTemplateSpecializationDecl *Spec
84 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
86 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
90 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
92 // If this class template specialization was instantiated from a
93 // specialized member that is a class template, we're done.
94 assert(Spec->getSpecializedTemplate() && "No class template?");
95 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
98 // Add template arguments from a function template specialization.
99 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
100 if (!RelativeToPrimary &&
101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
106 if (const TemplateArgumentList *TemplateArgs
107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
109 Result.addOuterTemplateArguments(TemplateArgs);
111 // If this function was instantiated from a specialized member that is
112 // a function template, we're done.
113 assert(Function->getPrimaryTemplate() && "No function template?");
114 if (Function->getPrimaryTemplate()->isMemberSpecialization())
116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
119 std::pair<const TemplateArgument *, unsigned>
120 Injected = FunTmpl->getInjectedTemplateArgs();
121 Result.addOuterTemplateArguments(Injected.first, Injected.second);
124 // If this is a friend declaration and it declares an entity at
125 // namespace scope, take arguments from its lexical parent
126 // instead of its semantic parent, unless of course the pattern we're
127 // instantiating actually comes from the file's context!
128 if (Function->getFriendObjectKind() &&
129 Function->getDeclContext()->isFileContext() &&
130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
131 Ctx = Function->getLexicalDeclContext();
132 RelativeToPrimary = false;
135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138 const TemplateSpecializationType *TST
139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141 if (ClassTemplate->isMemberSpecialization())
146 Ctx = Ctx->getParent();
147 RelativeToPrimary = false;
153 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
155 case TemplateInstantiation:
156 case ExceptionSpecInstantiation:
157 case DefaultTemplateArgumentInstantiation:
158 case DefaultFunctionArgumentInstantiation:
161 case ExplicitTemplateArgumentSubstitution:
162 case DeducedTemplateArgumentSubstitution:
163 case PriorTemplateArgumentSubstitution:
164 case DefaultTemplateArgumentChecking:
168 llvm_unreachable("Invalid InstantiationKind!");
171 Sema::InstantiatingTemplate::
172 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
174 SourceRange InstantiationRange)
176 SavedInNonInstantiationSFINAEContext(
177 SemaRef.InNonInstantiationSFINAEContext)
179 Invalid = CheckInstantiationDepth(PointOfInstantiation,
182 ActiveTemplateInstantiation Inst;
183 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
184 Inst.PointOfInstantiation = PointOfInstantiation;
185 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
186 Inst.TemplateArgs = 0;
187 Inst.NumTemplateArgs = 0;
188 Inst.InstantiationRange = InstantiationRange;
189 SemaRef.InNonInstantiationSFINAEContext = false;
190 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
194 Sema::InstantiatingTemplate::
195 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
196 FunctionDecl *Entity, ExceptionSpecification,
197 SourceRange InstantiationRange)
199 SavedInNonInstantiationSFINAEContext(
200 SemaRef.InNonInstantiationSFINAEContext)
202 Invalid = CheckInstantiationDepth(PointOfInstantiation,
205 ActiveTemplateInstantiation Inst;
206 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
207 Inst.PointOfInstantiation = PointOfInstantiation;
208 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
209 Inst.TemplateArgs = 0;
210 Inst.NumTemplateArgs = 0;
211 Inst.InstantiationRange = InstantiationRange;
212 SemaRef.InNonInstantiationSFINAEContext = false;
213 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
217 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
218 SourceLocation PointOfInstantiation,
219 TemplateDecl *Template,
220 const TemplateArgument *TemplateArgs,
221 unsigned NumTemplateArgs,
222 SourceRange InstantiationRange)
224 SavedInNonInstantiationSFINAEContext(
225 SemaRef.InNonInstantiationSFINAEContext)
227 Invalid = CheckInstantiationDepth(PointOfInstantiation,
230 ActiveTemplateInstantiation Inst;
232 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
233 Inst.PointOfInstantiation = PointOfInstantiation;
234 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
235 Inst.TemplateArgs = TemplateArgs;
236 Inst.NumTemplateArgs = NumTemplateArgs;
237 Inst.InstantiationRange = InstantiationRange;
238 SemaRef.InNonInstantiationSFINAEContext = false;
239 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
243 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
244 SourceLocation PointOfInstantiation,
245 FunctionTemplateDecl *FunctionTemplate,
246 const TemplateArgument *TemplateArgs,
247 unsigned NumTemplateArgs,
248 ActiveTemplateInstantiation::InstantiationKind Kind,
249 sema::TemplateDeductionInfo &DeductionInfo,
250 SourceRange InstantiationRange)
252 SavedInNonInstantiationSFINAEContext(
253 SemaRef.InNonInstantiationSFINAEContext)
255 Invalid = CheckInstantiationDepth(PointOfInstantiation,
258 ActiveTemplateInstantiation Inst;
260 Inst.PointOfInstantiation = PointOfInstantiation;
261 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
262 Inst.TemplateArgs = TemplateArgs;
263 Inst.NumTemplateArgs = NumTemplateArgs;
264 Inst.DeductionInfo = &DeductionInfo;
265 Inst.InstantiationRange = InstantiationRange;
266 SemaRef.InNonInstantiationSFINAEContext = false;
267 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
269 if (!Inst.isInstantiationRecord())
270 ++SemaRef.NonInstantiationEntries;
274 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
275 SourceLocation PointOfInstantiation,
276 ClassTemplatePartialSpecializationDecl *PartialSpec,
277 const TemplateArgument *TemplateArgs,
278 unsigned NumTemplateArgs,
279 sema::TemplateDeductionInfo &DeductionInfo,
280 SourceRange InstantiationRange)
282 SavedInNonInstantiationSFINAEContext(
283 SemaRef.InNonInstantiationSFINAEContext)
287 ActiveTemplateInstantiation Inst;
288 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
289 Inst.PointOfInstantiation = PointOfInstantiation;
290 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
291 Inst.TemplateArgs = TemplateArgs;
292 Inst.NumTemplateArgs = NumTemplateArgs;
293 Inst.DeductionInfo = &DeductionInfo;
294 Inst.InstantiationRange = InstantiationRange;
295 SemaRef.InNonInstantiationSFINAEContext = false;
296 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
298 assert(!Inst.isInstantiationRecord());
299 ++SemaRef.NonInstantiationEntries;
302 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
303 SourceLocation PointOfInstantiation,
305 const TemplateArgument *TemplateArgs,
306 unsigned NumTemplateArgs,
307 SourceRange InstantiationRange)
309 SavedInNonInstantiationSFINAEContext(
310 SemaRef.InNonInstantiationSFINAEContext)
312 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
315 ActiveTemplateInstantiation Inst;
317 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
318 Inst.PointOfInstantiation = PointOfInstantiation;
319 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
320 Inst.TemplateArgs = TemplateArgs;
321 Inst.NumTemplateArgs = NumTemplateArgs;
322 Inst.InstantiationRange = InstantiationRange;
323 SemaRef.InNonInstantiationSFINAEContext = false;
324 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
328 Sema::InstantiatingTemplate::
329 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
331 NonTypeTemplateParmDecl *Param,
332 const TemplateArgument *TemplateArgs,
333 unsigned NumTemplateArgs,
334 SourceRange InstantiationRange)
336 SavedInNonInstantiationSFINAEContext(
337 SemaRef.InNonInstantiationSFINAEContext)
341 ActiveTemplateInstantiation Inst;
342 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
343 Inst.PointOfInstantiation = PointOfInstantiation;
344 Inst.Template = Template;
345 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
346 Inst.TemplateArgs = TemplateArgs;
347 Inst.NumTemplateArgs = NumTemplateArgs;
348 Inst.InstantiationRange = InstantiationRange;
349 SemaRef.InNonInstantiationSFINAEContext = false;
350 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
352 assert(!Inst.isInstantiationRecord());
353 ++SemaRef.NonInstantiationEntries;
356 Sema::InstantiatingTemplate::
357 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
359 TemplateTemplateParmDecl *Param,
360 const TemplateArgument *TemplateArgs,
361 unsigned NumTemplateArgs,
362 SourceRange InstantiationRange)
364 SavedInNonInstantiationSFINAEContext(
365 SemaRef.InNonInstantiationSFINAEContext)
368 ActiveTemplateInstantiation Inst;
369 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
370 Inst.PointOfInstantiation = PointOfInstantiation;
371 Inst.Template = Template;
372 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
373 Inst.TemplateArgs = TemplateArgs;
374 Inst.NumTemplateArgs = NumTemplateArgs;
375 Inst.InstantiationRange = InstantiationRange;
376 SemaRef.InNonInstantiationSFINAEContext = false;
377 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
379 assert(!Inst.isInstantiationRecord());
380 ++SemaRef.NonInstantiationEntries;
383 Sema::InstantiatingTemplate::
384 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
385 TemplateDecl *Template,
387 const TemplateArgument *TemplateArgs,
388 unsigned NumTemplateArgs,
389 SourceRange InstantiationRange)
391 SavedInNonInstantiationSFINAEContext(
392 SemaRef.InNonInstantiationSFINAEContext)
396 ActiveTemplateInstantiation Inst;
397 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
398 Inst.PointOfInstantiation = PointOfInstantiation;
399 Inst.Template = Template;
400 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
401 Inst.TemplateArgs = TemplateArgs;
402 Inst.NumTemplateArgs = NumTemplateArgs;
403 Inst.InstantiationRange = InstantiationRange;
404 SemaRef.InNonInstantiationSFINAEContext = false;
405 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
407 assert(!Inst.isInstantiationRecord());
408 ++SemaRef.NonInstantiationEntries;
411 void Sema::InstantiatingTemplate::Clear() {
413 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
414 assert(SemaRef.NonInstantiationEntries > 0);
415 --SemaRef.NonInstantiationEntries;
417 SemaRef.InNonInstantiationSFINAEContext
418 = SavedInNonInstantiationSFINAEContext;
419 SemaRef.ActiveTemplateInstantiations.pop_back();
424 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
425 SourceLocation PointOfInstantiation,
426 SourceRange InstantiationRange) {
427 assert(SemaRef.NonInstantiationEntries <=
428 SemaRef.ActiveTemplateInstantiations.size());
429 if ((SemaRef.ActiveTemplateInstantiations.size() -
430 SemaRef.NonInstantiationEntries)
431 <= SemaRef.getLangOpts().InstantiationDepth)
434 SemaRef.Diag(PointOfInstantiation,
435 diag::err_template_recursion_depth_exceeded)
436 << SemaRef.getLangOpts().InstantiationDepth
437 << InstantiationRange;
438 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
439 << SemaRef.getLangOpts().InstantiationDepth;
443 /// \brief Prints the current instantiation stack through a series of
445 void Sema::PrintInstantiationStack() {
446 // Determine which template instantiations to skip, if any.
447 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
448 unsigned Limit = Diags.getTemplateBacktraceLimit();
449 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
450 SkipStart = Limit / 2 + Limit % 2;
451 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
454 // FIXME: In all of these cases, we need to show the template arguments
455 unsigned InstantiationIdx = 0;
456 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
457 Active = ActiveTemplateInstantiations.rbegin(),
458 ActiveEnd = ActiveTemplateInstantiations.rend();
460 ++Active, ++InstantiationIdx) {
461 // Skip this instantiation?
462 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
463 if (InstantiationIdx == SkipStart) {
464 // Note that we're skipping instantiations.
465 Diags.Report(Active->PointOfInstantiation,
466 diag::note_instantiation_contexts_suppressed)
467 << unsigned(ActiveTemplateInstantiations.size() - Limit);
472 switch (Active->Kind) {
473 case ActiveTemplateInstantiation::TemplateInstantiation: {
474 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
475 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
476 unsigned DiagID = diag::note_template_member_class_here;
477 if (isa<ClassTemplateSpecializationDecl>(Record))
478 DiagID = diag::note_template_class_instantiation_here;
479 Diags.Report(Active->PointOfInstantiation, DiagID)
480 << Context.getTypeDeclType(Record)
481 << Active->InstantiationRange;
482 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
484 if (Function->getPrimaryTemplate())
485 DiagID = diag::note_function_template_spec_here;
487 DiagID = diag::note_template_member_function_here;
488 Diags.Report(Active->PointOfInstantiation, DiagID)
490 << Active->InstantiationRange;
491 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
492 Diags.Report(Active->PointOfInstantiation,
493 diag::note_template_static_data_member_def_here)
495 << Active->InstantiationRange;
496 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
497 Diags.Report(Active->PointOfInstantiation,
498 diag::note_template_enum_def_here)
500 << Active->InstantiationRange;
502 Diags.Report(Active->PointOfInstantiation,
503 diag::note_template_type_alias_instantiation_here)
504 << cast<TypeAliasTemplateDecl>(D)
505 << Active->InstantiationRange;
510 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
511 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
512 std::string TemplateArgsStr
513 = TemplateSpecializationType::PrintTemplateArgumentList(
514 Active->TemplateArgs,
515 Active->NumTemplateArgs,
516 getPrintingPolicy());
517 Diags.Report(Active->PointOfInstantiation,
518 diag::note_default_arg_instantiation_here)
519 << (Template->getNameAsString() + TemplateArgsStr)
520 << Active->InstantiationRange;
524 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
525 FunctionTemplateDecl *FnTmpl
526 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
527 Diags.Report(Active->PointOfInstantiation,
528 diag::note_explicit_template_arg_substitution_here)
530 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
531 Active->TemplateArgs,
532 Active->NumTemplateArgs)
533 << Active->InstantiationRange;
537 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
538 if (ClassTemplatePartialSpecializationDecl *PartialSpec
539 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
540 (Decl *)Active->Entity)) {
541 Diags.Report(Active->PointOfInstantiation,
542 diag::note_partial_spec_deduct_instantiation_here)
543 << Context.getTypeDeclType(PartialSpec)
544 << getTemplateArgumentBindingsText(
545 PartialSpec->getTemplateParameters(),
546 Active->TemplateArgs,
547 Active->NumTemplateArgs)
548 << Active->InstantiationRange;
550 FunctionTemplateDecl *FnTmpl
551 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
552 Diags.Report(Active->PointOfInstantiation,
553 diag::note_function_template_deduction_instantiation_here)
555 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
556 Active->TemplateArgs,
557 Active->NumTemplateArgs)
558 << Active->InstantiationRange;
562 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
563 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
564 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
566 std::string TemplateArgsStr
567 = TemplateSpecializationType::PrintTemplateArgumentList(
568 Active->TemplateArgs,
569 Active->NumTemplateArgs,
570 getPrintingPolicy());
571 Diags.Report(Active->PointOfInstantiation,
572 diag::note_default_function_arg_instantiation_here)
573 << (FD->getNameAsString() + TemplateArgsStr)
574 << Active->InstantiationRange;
578 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
579 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
581 if (!Parm->getName().empty())
582 Name = std::string(" '") + Parm->getName().str() + "'";
584 TemplateParameterList *TemplateParams = 0;
585 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
586 TemplateParams = Template->getTemplateParameters();
589 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
590 ->getTemplateParameters();
591 Diags.Report(Active->PointOfInstantiation,
592 diag::note_prior_template_arg_substitution)
593 << isa<TemplateTemplateParmDecl>(Parm)
595 << getTemplateArgumentBindingsText(TemplateParams,
596 Active->TemplateArgs,
597 Active->NumTemplateArgs)
598 << Active->InstantiationRange;
602 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
603 TemplateParameterList *TemplateParams = 0;
604 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
605 TemplateParams = Template->getTemplateParameters();
608 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
609 ->getTemplateParameters();
611 Diags.Report(Active->PointOfInstantiation,
612 diag::note_template_default_arg_checking)
613 << getTemplateArgumentBindingsText(TemplateParams,
614 Active->TemplateArgs,
615 Active->NumTemplateArgs)
616 << Active->InstantiationRange;
620 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
621 Diags.Report(Active->PointOfInstantiation,
622 diag::note_template_exception_spec_instantiation_here)
623 << cast<FunctionDecl>((Decl *)Active->Entity)
624 << Active->InstantiationRange;
630 llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
631 if (InNonInstantiationSFINAEContext)
632 return llvm::Optional<TemplateDeductionInfo *>(0);
634 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
635 Active = ActiveTemplateInstantiations.rbegin(),
636 ActiveEnd = ActiveTemplateInstantiations.rend();
640 switch(Active->Kind) {
641 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
642 case ActiveTemplateInstantiation::TemplateInstantiation:
643 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
644 // This is a template instantiation, so there is no SFINAE.
645 return llvm::Optional<TemplateDeductionInfo *>();
647 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
648 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
649 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
650 // A default template argument instantiation and substitution into
651 // template parameters with arguments for prior parameters may or may
652 // not be a SFINAE context; look further up the stack.
655 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
656 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
657 // We're either substitution explicitly-specified template arguments
658 // or deduced template arguments, so SFINAE applies.
659 assert(Active->DeductionInfo && "Missing deduction info pointer");
660 return Active->DeductionInfo;
664 return llvm::Optional<TemplateDeductionInfo *>();
667 /// \brief Retrieve the depth and index of a parameter pack.
668 static std::pair<unsigned, unsigned>
669 getDepthAndIndex(NamedDecl *ND) {
670 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
671 return std::make_pair(TTP->getDepth(), TTP->getIndex());
673 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
674 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
676 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
677 return std::make_pair(TTP->getDepth(), TTP->getIndex());
680 //===----------------------------------------------------------------------===/
681 // Template Instantiation for Types
682 //===----------------------------------------------------------------------===/
684 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
685 const MultiLevelTemplateArgumentList &TemplateArgs;
687 DeclarationName Entity;
690 typedef TreeTransform<TemplateInstantiator> inherited;
692 TemplateInstantiator(Sema &SemaRef,
693 const MultiLevelTemplateArgumentList &TemplateArgs,
695 DeclarationName Entity)
696 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
699 /// \brief Determine whether the given type \p T has already been
702 /// For the purposes of template instantiation, a type has already been
703 /// transformed if it is NULL or if it is not dependent.
704 bool AlreadyTransformed(QualType T);
706 /// \brief Returns the location of the entity being instantiated, if known.
707 SourceLocation getBaseLocation() { return Loc; }
709 /// \brief Returns the name of the entity being instantiated, if any.
710 DeclarationName getBaseEntity() { return Entity; }
712 /// \brief Sets the "base" location and entity when that
713 /// information is known based on another transformation.
714 void setBase(SourceLocation Loc, DeclarationName Entity) {
716 this->Entity = Entity;
719 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
720 SourceRange PatternRange,
721 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
723 bool &RetainExpansion,
724 llvm::Optional<unsigned> &NumExpansions) {
725 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
726 PatternRange, Unexpanded,
733 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
734 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
737 TemplateArgument ForgetPartiallySubstitutedPack() {
738 TemplateArgument Result;
739 if (NamedDecl *PartialPack
740 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
741 MultiLevelTemplateArgumentList &TemplateArgs
742 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
743 unsigned Depth, Index;
744 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
745 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
746 Result = TemplateArgs(Depth, Index);
747 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
754 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
758 if (NamedDecl *PartialPack
759 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
760 MultiLevelTemplateArgumentList &TemplateArgs
761 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
762 unsigned Depth, Index;
763 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
764 TemplateArgs.setArgument(Depth, Index, Arg);
768 /// \brief Transform the given declaration by instantiating a reference to
769 /// this declaration.
770 Decl *TransformDecl(SourceLocation Loc, Decl *D);
772 void transformAttrs(Decl *Old, Decl *New) {
773 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
776 void transformedLocalDecl(Decl *Old, Decl *New) {
777 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
780 /// \brief Transform the definition of the given declaration by
781 /// instantiating it.
782 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
784 /// \bried Transform the first qualifier within a scope by instantiating the
786 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
788 /// \brief Rebuild the exception declaration and register the declaration
789 /// as an instantiated local.
790 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
791 TypeSourceInfo *Declarator,
792 SourceLocation StartLoc,
793 SourceLocation NameLoc,
794 IdentifierInfo *Name);
796 /// \brief Rebuild the Objective-C exception declaration and register the
797 /// declaration as an instantiated local.
798 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
799 TypeSourceInfo *TSInfo, QualType T);
801 /// \brief Check for tag mismatches when instantiating an
803 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
804 ElaboratedTypeKeyword Keyword,
805 NestedNameSpecifierLoc QualifierLoc,
808 TemplateName TransformTemplateName(CXXScopeSpec &SS,
810 SourceLocation NameLoc,
811 QualType ObjectType = QualType(),
812 NamedDecl *FirstQualifierInScope = 0);
814 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
815 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
816 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
817 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
818 NonTypeTemplateParmDecl *D);
819 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
820 SubstNonTypeTemplateParmPackExpr *E);
822 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
823 FunctionProtoTypeLoc TL);
824 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
825 FunctionProtoTypeLoc TL,
826 CXXRecordDecl *ThisContext,
827 unsigned ThisTypeQuals);
829 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
831 llvm::Optional<unsigned> NumExpansions,
832 bool ExpectParameterPack);
834 /// \brief Transforms a template type parameter type by performing
835 /// substitution of the corresponding template type argument.
836 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
837 TemplateTypeParmTypeLoc TL);
839 /// \brief Transforms an already-substituted template type parameter pack
840 /// into either itself (if we aren't substituting into its pack expansion)
841 /// or the appropriate substituted argument.
842 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
843 SubstTemplateTypeParmPackTypeLoc TL);
845 ExprResult TransformCallExpr(CallExpr *CE) {
846 getSema().CallsUndergoingInstantiation.push_back(CE);
848 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
849 getSema().CallsUndergoingInstantiation.pop_back();
854 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
856 const TemplateArgument &arg);
860 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
864 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
867 getSema().MarkDeclarationsReferencedInType(Loc, T);
871 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
875 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
876 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
877 // If the corresponding template argument is NULL or non-existent, it's
878 // because we are performing instantiation from explicitly-specified
879 // template arguments in a function template, but there were some
880 // arguments left unspecified.
881 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
885 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
887 if (TTP->isParameterPack()) {
888 assert(Arg.getKind() == TemplateArgument::Pack &&
889 "Missing argument pack");
891 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
892 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
893 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
896 TemplateName Template = Arg.getAsTemplate();
897 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
898 "Wrong kind of template template argument");
899 return Template.getAsTemplateDecl();
902 // Fall through to find the instantiated declaration for this template
903 // template parameter.
906 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
909 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
910 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
914 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
919 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
920 SourceLocation Loc) {
921 // If the first part of the nested-name-specifier was a template type
922 // parameter, instantiate that type parameter down to a tag type.
923 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
924 const TemplateTypeParmType *TTP
925 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
927 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
928 // FIXME: This needs testing w/ member access expressions.
929 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
931 if (TTP->isParameterPack()) {
932 assert(Arg.getKind() == TemplateArgument::Pack &&
933 "Missing argument pack");
935 if (getSema().ArgumentPackSubstitutionIndex == -1)
938 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
939 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
942 QualType T = Arg.getAsType();
944 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
946 if (const TagType *Tag = T->getAs<TagType>())
947 return Tag->getDecl();
949 // The resulting type is not a tag; complain.
950 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
955 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
959 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
960 TypeSourceInfo *Declarator,
961 SourceLocation StartLoc,
962 SourceLocation NameLoc,
963 IdentifierInfo *Name) {
964 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
965 StartLoc, NameLoc, Name);
967 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
971 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
972 TypeSourceInfo *TSInfo,
974 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
976 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
981 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
982 ElaboratedTypeKeyword Keyword,
983 NestedNameSpecifierLoc QualifierLoc,
985 if (const TagType *TT = T->getAs<TagType>()) {
986 TagDecl* TD = TT->getDecl();
988 SourceLocation TagLocation = KeywordLoc;
990 // FIXME: type might be anonymous.
991 IdentifierInfo *Id = TD->getIdentifier();
993 // TODO: should we even warn on struct/class mismatches for this? Seems
994 // like it's likely to produce a lot of spurious errors.
995 if (Keyword != ETK_None && Keyword != ETK_Typename) {
996 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
997 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
999 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1001 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1003 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1008 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1014 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1016 SourceLocation NameLoc,
1017 QualType ObjectType,
1018 NamedDecl *FirstQualifierInScope) {
1019 if (TemplateTemplateParmDecl *TTP
1020 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1021 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1022 // If the corresponding template argument is NULL or non-existent, it's
1023 // because we are performing instantiation from explicitly-specified
1024 // template arguments in a function template, but there were some
1025 // arguments left unspecified.
1026 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1027 TTP->getPosition()))
1030 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1032 if (TTP->isParameterPack()) {
1033 assert(Arg.getKind() == TemplateArgument::Pack &&
1034 "Missing argument pack");
1036 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1037 // We have the template argument pack to substitute, but we're not
1038 // actually expanding the enclosing pack expansion yet. So, just
1039 // keep the entire argument pack.
1040 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1043 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1044 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1047 TemplateName Template = Arg.getAsTemplate();
1048 assert(!Template.isNull() && "Null template template argument");
1050 // We don't ever want to substitute for a qualified template name, since
1051 // the qualifier is handled separately. So, look through the qualified
1052 // template name to its underlying declaration.
1053 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1054 Template = TemplateName(QTN->getTemplateDecl());
1056 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1061 if (SubstTemplateTemplateParmPackStorage *SubstPack
1062 = Name.getAsSubstTemplateTemplateParmPack()) {
1063 if (getSema().ArgumentPackSubstitutionIndex == -1)
1066 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1067 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1068 "Pack substitution index out-of-range");
1069 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1073 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1074 FirstQualifierInScope);
1078 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1079 if (!E->isTypeDependent())
1080 return SemaRef.Owned(E);
1082 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1083 assert(currentDecl && "Must have current function declaration when "
1086 PredefinedExpr::IdentType IT = E->getIdentType();
1088 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
1090 llvm::APInt LengthI(32, Length + 1);
1091 QualType ResTy = getSema().Context.CharTy.withConst();
1092 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1093 ArrayType::Normal, 0);
1094 PredefinedExpr *PE =
1095 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1096 return getSema().Owned(PE);
1100 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1101 NonTypeTemplateParmDecl *NTTP) {
1102 // If the corresponding template argument is NULL or non-existent, it's
1103 // because we are performing instantiation from explicitly-specified
1104 // template arguments in a function template, but there were some
1105 // arguments left unspecified.
1106 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1107 NTTP->getPosition()))
1108 return SemaRef.Owned(E);
1110 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1111 if (NTTP->isParameterPack()) {
1112 assert(Arg.getKind() == TemplateArgument::Pack &&
1113 "Missing argument pack");
1115 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1116 // We have an argument pack, but we can't select a particular argument
1117 // out of it yet. Therefore, we'll build an expression to hold on to that
1119 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1121 NTTP->getDeclName());
1122 if (TargetType.isNull())
1125 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1131 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1132 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1135 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1138 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1139 NonTypeTemplateParmDecl *parm,
1141 const TemplateArgument &arg) {
1145 // The template argument itself might be an expression, in which
1146 // case we just return that expression.
1147 if (arg.getKind() == TemplateArgument::Expression) {
1148 Expr *argExpr = arg.getAsExpr();
1149 result = SemaRef.Owned(argExpr);
1150 type = argExpr->getType();
1152 } else if (arg.getKind() == TemplateArgument::Declaration) {
1154 if (Decl *D = arg.getAsDecl()) {
1155 VD = cast<ValueDecl>(D);
1157 // Find the instantiation of the template argument. This is
1158 // required for nested templates.
1159 VD = cast_or_null<ValueDecl>(
1160 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1164 // Propagate NULL template argument.
1168 // Derive the type we want the substituted decl to have. This had
1169 // better be non-dependent, or these checks will have serious problems.
1170 if (parm->isExpandedParameterPack()) {
1171 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1172 } else if (parm->isParameterPack() &&
1173 isa<PackExpansionType>(parm->getType())) {
1174 type = SemaRef.SubstType(
1175 cast<PackExpansionType>(parm->getType())->getPattern(),
1176 TemplateArgs, loc, parm->getDeclName());
1178 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1179 loc, parm->getDeclName());
1181 assert(!type.isNull() && "type substitution failed for param type");
1182 assert(!type->isDependentType() && "param type still dependent");
1183 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1185 if (!result.isInvalid()) type = result.get()->getType();
1187 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1189 // Note that this type can be different from the type of 'result',
1190 // e.g. if it's an enum type.
1191 type = arg.getIntegralType();
1193 if (result.isInvalid()) return ExprError();
1195 Expr *resultExpr = result.take();
1196 return SemaRef.Owned(new (SemaRef.Context)
1197 SubstNonTypeTemplateParmExpr(type,
1198 resultExpr->getValueKind(),
1199 loc, parm, resultExpr));
1203 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1204 SubstNonTypeTemplateParmPackExpr *E) {
1205 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1206 // We aren't expanding the parameter pack, so just return ourselves.
1207 return getSema().Owned(E);
1210 const TemplateArgument &ArgPack = E->getArgumentPack();
1211 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1212 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1214 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1215 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1216 E->getParameterPackLocation(),
1221 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1222 NamedDecl *D = E->getDecl();
1223 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1224 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1225 return TransformTemplateParmRefExpr(E, NTTP);
1227 // We have a non-type template parameter that isn't fully substituted;
1228 // FindInstantiatedDecl will find it in the local instantiation scope.
1231 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1234 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1235 CXXDefaultArgExpr *E) {
1236 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1237 getDescribedFunctionTemplate() &&
1238 "Default arg expressions are never formed in dependent cases.");
1239 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1240 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1244 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1245 FunctionProtoTypeLoc TL) {
1246 // We need a local instantiation scope for this function prototype.
1247 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1248 return inherited::TransformFunctionProtoType(TLB, TL);
1251 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1252 FunctionProtoTypeLoc TL,
1253 CXXRecordDecl *ThisContext,
1254 unsigned ThisTypeQuals) {
1255 // We need a local instantiation scope for this function prototype.
1256 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1257 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1262 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1263 int indexAdjustment,
1264 llvm::Optional<unsigned> NumExpansions,
1265 bool ExpectParameterPack) {
1266 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1267 NumExpansions, ExpectParameterPack);
1271 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1272 TemplateTypeParmTypeLoc TL) {
1273 const TemplateTypeParmType *T = TL.getTypePtr();
1274 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1275 // Replace the template type parameter with its corresponding
1276 // template argument.
1278 // If the corresponding template argument is NULL or doesn't exist, it's
1279 // because we are performing instantiation from explicitly-specified
1280 // template arguments in a function template class, but there were some
1281 // arguments left unspecified.
1282 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1283 TemplateTypeParmTypeLoc NewTL
1284 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1285 NewTL.setNameLoc(TL.getNameLoc());
1286 return TL.getType();
1289 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1291 if (T->isParameterPack()) {
1292 assert(Arg.getKind() == TemplateArgument::Pack &&
1293 "Missing argument pack");
1295 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1296 // We have the template argument pack, but we're not expanding the
1297 // enclosing pack expansion yet. Just save the template argument
1298 // pack for later substitution.
1300 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1301 SubstTemplateTypeParmPackTypeLoc NewTL
1302 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1303 NewTL.setNameLoc(TL.getNameLoc());
1307 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1308 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1311 assert(Arg.getKind() == TemplateArgument::Type &&
1312 "Template argument kind mismatch");
1314 QualType Replacement = Arg.getAsType();
1316 // TODO: only do this uniquing once, at the start of instantiation.
1318 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1319 SubstTemplateTypeParmTypeLoc NewTL
1320 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1321 NewTL.setNameLoc(TL.getNameLoc());
1325 // The template type parameter comes from an inner template (e.g.,
1326 // the template parameter list of a member template inside the
1327 // template we are instantiating). Create a new template type
1328 // parameter with the template "level" reduced by one.
1329 TemplateTypeParmDecl *NewTTPDecl = 0;
1330 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1331 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1332 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1335 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1336 - TemplateArgs.getNumLevels(),
1338 T->isParameterPack(),
1340 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1341 NewTL.setNameLoc(TL.getNameLoc());
1346 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1347 TypeLocBuilder &TLB,
1348 SubstTemplateTypeParmPackTypeLoc TL) {
1349 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1350 // We aren't expanding the parameter pack, so just return ourselves.
1351 SubstTemplateTypeParmPackTypeLoc NewTL
1352 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1353 NewTL.setNameLoc(TL.getNameLoc());
1354 return TL.getType();
1357 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1358 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1359 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1361 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1362 Result = getSema().Context.getSubstTemplateTypeParmType(
1363 TL.getTypePtr()->getReplacedParameter(),
1365 SubstTemplateTypeParmTypeLoc NewTL
1366 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1367 NewTL.setNameLoc(TL.getNameLoc());
1371 /// \brief Perform substitution on the type T with a given set of template
1374 /// This routine substitutes the given template arguments into the
1375 /// type T and produces the instantiated type.
1377 /// \param T the type into which the template arguments will be
1378 /// substituted. If this type is not dependent, it will be returned
1381 /// \param TemplateArgs the template arguments that will be
1382 /// substituted for the top-level template parameters within T.
1384 /// \param Loc the location in the source code where this substitution
1385 /// is being performed. It will typically be the location of the
1386 /// declarator (if we're instantiating the type of some declaration)
1387 /// or the location of the type in the source code (if, e.g., we're
1388 /// instantiating the type of a cast expression).
1390 /// \param Entity the name of the entity associated with a declaration
1391 /// being instantiated (if any). May be empty to indicate that there
1392 /// is no such entity (if, e.g., this is a type that occurs as part of
1393 /// a cast expression) or that the entity has no name (e.g., an
1394 /// unnamed function parameter).
1396 /// \returns If the instantiation succeeds, the instantiated
1397 /// type. Otherwise, produces diagnostics and returns a NULL type.
1398 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1399 const MultiLevelTemplateArgumentList &Args,
1401 DeclarationName Entity) {
1402 assert(!ActiveTemplateInstantiations.empty() &&
1403 "Cannot perform an instantiation without some context on the "
1404 "instantiation stack");
1406 if (!T->getType()->isInstantiationDependentType() &&
1407 !T->getType()->isVariablyModifiedType())
1410 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1411 return Instantiator.TransformType(T);
1414 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1415 const MultiLevelTemplateArgumentList &Args,
1417 DeclarationName Entity) {
1418 assert(!ActiveTemplateInstantiations.empty() &&
1419 "Cannot perform an instantiation without some context on the "
1420 "instantiation stack");
1422 if (TL.getType().isNull())
1425 if (!TL.getType()->isInstantiationDependentType() &&
1426 !TL.getType()->isVariablyModifiedType()) {
1427 // FIXME: Make a copy of the TypeLoc data here, so that we can
1428 // return a new TypeSourceInfo. Inefficient!
1430 TLB.pushFullCopy(TL);
1431 return TLB.getTypeSourceInfo(Context, TL.getType());
1434 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1436 TLB.reserve(TL.getFullDataSize());
1437 QualType Result = Instantiator.TransformType(TLB, TL);
1438 if (Result.isNull())
1441 return TLB.getTypeSourceInfo(Context, Result);
1444 /// Deprecated form of the above.
1445 QualType Sema::SubstType(QualType T,
1446 const MultiLevelTemplateArgumentList &TemplateArgs,
1447 SourceLocation Loc, DeclarationName Entity) {
1448 assert(!ActiveTemplateInstantiations.empty() &&
1449 "Cannot perform an instantiation without some context on the "
1450 "instantiation stack");
1452 // If T is not a dependent type or a variably-modified type, there
1453 // is nothing to do.
1454 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1457 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1458 return Instantiator.TransformType(T);
1461 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1462 if (T->getType()->isInstantiationDependentType() ||
1463 T->getType()->isVariablyModifiedType())
1466 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1467 if (!isa<FunctionProtoTypeLoc>(TL))
1470 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1471 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1472 ParmVarDecl *P = FP.getArg(I);
1474 // The parameter's type as written might be dependent even if the
1475 // decayed type was not dependent.
1476 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1477 if (TSInfo->getType()->isInstantiationDependentType())
1480 // TODO: currently we always rebuild expressions. When we
1481 // properly get lazier about this, we should use the same
1482 // logic to avoid rebuilding prototypes here.
1483 if (P->hasDefaultArg())
1490 /// A form of SubstType intended specifically for instantiating the
1491 /// type of a FunctionDecl. Its purpose is solely to force the
1492 /// instantiation of default-argument expressions.
1493 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1494 const MultiLevelTemplateArgumentList &Args,
1496 DeclarationName Entity,
1497 CXXRecordDecl *ThisContext,
1498 unsigned ThisTypeQuals) {
1499 assert(!ActiveTemplateInstantiations.empty() &&
1500 "Cannot perform an instantiation without some context on the "
1501 "instantiation stack");
1503 if (!NeedsInstantiationAsFunctionType(T))
1506 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1510 TypeLoc TL = T->getTypeLoc();
1511 TLB.reserve(TL.getFullDataSize());
1515 if (FunctionProtoTypeLoc *Proto = dyn_cast<FunctionProtoTypeLoc>(&TL)) {
1516 Result = Instantiator.TransformFunctionProtoType(TLB, *Proto, ThisContext,
1519 Result = Instantiator.TransformType(TLB, TL);
1521 if (Result.isNull())
1524 return TLB.getTypeSourceInfo(Context, Result);
1527 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1528 const MultiLevelTemplateArgumentList &TemplateArgs,
1529 int indexAdjustment,
1530 llvm::Optional<unsigned> NumExpansions,
1531 bool ExpectParameterPack) {
1532 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1533 TypeSourceInfo *NewDI = 0;
1535 TypeLoc OldTL = OldDI->getTypeLoc();
1536 if (isa<PackExpansionTypeLoc>(OldTL)) {
1537 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
1539 // We have a function parameter pack. Substitute into the pattern of the
1541 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1542 OldParm->getLocation(), OldParm->getDeclName());
1546 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1547 // We still have unexpanded parameter packs, which means that
1548 // our function parameter is still a function parameter pack.
1549 // Therefore, make its type a pack expansion type.
1550 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1552 } else if (ExpectParameterPack) {
1553 // We expected to get a parameter pack but didn't (because the type
1554 // itself is not a pack expansion type), so complain. This can occur when
1555 // the substitution goes through an alias template that "loses" the
1557 Diag(OldParm->getLocation(),
1558 diag::err_function_parameter_pack_without_parameter_packs)
1559 << NewDI->getType();
1563 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1564 OldParm->getDeclName());
1570 if (NewDI->getType()->isVoidType()) {
1571 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1575 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1576 OldParm->getInnerLocStart(),
1577 OldParm->getLocation(),
1578 OldParm->getIdentifier(),
1579 NewDI->getType(), NewDI,
1580 OldParm->getStorageClass(),
1581 OldParm->getStorageClassAsWritten());
1585 // Mark the (new) default argument as uninstantiated (if any).
1586 if (OldParm->hasUninstantiatedDefaultArg()) {
1587 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1588 NewParm->setUninstantiatedDefaultArg(Arg);
1589 } else if (OldParm->hasUnparsedDefaultArg()) {
1590 NewParm->setUnparsedDefaultArg();
1591 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1592 } else if (Expr *Arg = OldParm->getDefaultArg())
1593 NewParm->setUninstantiatedDefaultArg(Arg);
1595 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1597 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1598 // Add the new parameter to the instantiated parameter pack.
1599 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1601 // Introduce an Old -> New mapping
1602 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1605 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1606 // can be anything, is this right ?
1607 NewParm->setDeclContext(CurContext);
1609 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1610 OldParm->getFunctionScopeIndex() + indexAdjustment);
1615 /// \brief Substitute the given template arguments into the given set of
1616 /// parameters, producing the set of parameter types that would be generated
1617 /// from such a substitution.
1618 bool Sema::SubstParmTypes(SourceLocation Loc,
1619 ParmVarDecl **Params, unsigned NumParams,
1620 const MultiLevelTemplateArgumentList &TemplateArgs,
1621 SmallVectorImpl<QualType> &ParamTypes,
1622 SmallVectorImpl<ParmVarDecl *> *OutParams) {
1623 assert(!ActiveTemplateInstantiations.empty() &&
1624 "Cannot perform an instantiation without some context on the "
1625 "instantiation stack");
1627 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1629 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
1630 ParamTypes, OutParams);
1633 /// \brief Perform substitution on the base class specifiers of the
1634 /// given class template specialization.
1636 /// Produces a diagnostic and returns true on error, returns false and
1637 /// attaches the instantiated base classes to the class template
1638 /// specialization if successful.
1640 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1641 CXXRecordDecl *Pattern,
1642 const MultiLevelTemplateArgumentList &TemplateArgs) {
1643 bool Invalid = false;
1644 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1645 for (ClassTemplateSpecializationDecl::base_class_iterator
1646 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
1647 Base != BaseEnd; ++Base) {
1648 if (!Base->getType()->isDependentType()) {
1649 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
1653 SourceLocation EllipsisLoc;
1654 TypeSourceInfo *BaseTypeLoc;
1655 if (Base->isPackExpansion()) {
1656 // This is a pack expansion. See whether we should expand it now, or
1657 // wait until later.
1658 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1659 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1661 bool ShouldExpand = false;
1662 bool RetainExpansion = false;
1663 llvm::Optional<unsigned> NumExpansions;
1664 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1665 Base->getSourceRange(),
1667 TemplateArgs, ShouldExpand,
1674 // If we should expand this pack expansion now, do so.
1676 for (unsigned I = 0; I != *NumExpansions; ++I) {
1677 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1679 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1681 Base->getSourceRange().getBegin(),
1688 if (CXXBaseSpecifier *InstantiatedBase
1689 = CheckBaseSpecifier(Instantiation,
1690 Base->getSourceRange(),
1692 Base->getAccessSpecifierAsWritten(),
1695 InstantiatedBases.push_back(InstantiatedBase);
1703 // The resulting base specifier will (still) be a pack expansion.
1704 EllipsisLoc = Base->getEllipsisLoc();
1705 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1706 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1708 Base->getSourceRange().getBegin(),
1711 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1713 Base->getSourceRange().getBegin(),
1722 if (CXXBaseSpecifier *InstantiatedBase
1723 = CheckBaseSpecifier(Instantiation,
1724 Base->getSourceRange(),
1726 Base->getAccessSpecifierAsWritten(),
1729 InstantiatedBases.push_back(InstantiatedBase);
1735 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1736 InstantiatedBases.size()))
1742 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1745 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1746 const MultiLevelTemplateArgumentList &TemplateArgs);
1750 /// Determine whether we would be unable to instantiate this template (because
1751 /// it either has no definition, or is in the process of being instantiated).
1752 static bool DiagnoseUninstantiableTemplate(Sema &S,
1753 SourceLocation PointOfInstantiation,
1754 TagDecl *Instantiation,
1755 bool InstantiatedFromMember,
1757 TagDecl *PatternDef,
1758 TemplateSpecializationKind TSK,
1759 bool Complain = true) {
1760 if (PatternDef && !PatternDef->isBeingDefined())
1763 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1765 } else if (PatternDef) {
1766 assert(PatternDef->isBeingDefined());
1767 S.Diag(PointOfInstantiation,
1768 diag::err_template_instantiate_within_definition)
1769 << (TSK != TSK_ImplicitInstantiation)
1770 << S.Context.getTypeDeclType(Instantiation);
1771 // Not much point in noting the template declaration here, since
1772 // we're lexically inside it.
1773 Instantiation->setInvalidDecl();
1774 } else if (InstantiatedFromMember) {
1775 S.Diag(PointOfInstantiation,
1776 diag::err_implicit_instantiate_member_undefined)
1777 << S.Context.getTypeDeclType(Instantiation);
1778 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1780 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1781 << (TSK != TSK_ImplicitInstantiation)
1782 << S.Context.getTypeDeclType(Instantiation);
1783 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1786 // In general, Instantiation isn't marked invalid to get more than one
1787 // error for multiple undefined instantiations. But the code that does
1788 // explicit declaration -> explicit definition conversion can't handle
1789 // invalid declarations, so mark as invalid in that case.
1790 if (TSK == TSK_ExplicitInstantiationDeclaration)
1791 Instantiation->setInvalidDecl();
1795 /// \brief Instantiate the definition of a class from a given pattern.
1797 /// \param PointOfInstantiation The point of instantiation within the
1800 /// \param Instantiation is the declaration whose definition is being
1801 /// instantiated. This will be either a class template specialization
1802 /// or a member class of a class template specialization.
1804 /// \param Pattern is the pattern from which the instantiation
1805 /// occurs. This will be either the declaration of a class template or
1806 /// the declaration of a member class of a class template.
1808 /// \param TemplateArgs The template arguments to be substituted into
1811 /// \param TSK the kind of implicit or explicit instantiation to perform.
1813 /// \param Complain whether to complain if the class cannot be instantiated due
1814 /// to the lack of a definition.
1816 /// \returns true if an error occurred, false otherwise.
1818 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1819 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1820 const MultiLevelTemplateArgumentList &TemplateArgs,
1821 TemplateSpecializationKind TSK,
1823 bool Invalid = false;
1825 CXXRecordDecl *PatternDef
1826 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1827 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1828 Instantiation->getInstantiatedFromMemberClass(),
1829 Pattern, PatternDef, TSK, Complain))
1831 Pattern = PatternDef;
1833 // \brief Record the point of instantiation.
1834 if (MemberSpecializationInfo *MSInfo
1835 = Instantiation->getMemberSpecializationInfo()) {
1836 MSInfo->setTemplateSpecializationKind(TSK);
1837 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1838 } else if (ClassTemplateSpecializationDecl *Spec
1839 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1840 Spec->setTemplateSpecializationKind(TSK);
1841 Spec->setPointOfInstantiation(PointOfInstantiation);
1844 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1848 // Enter the scope of this instantiation. We don't use
1849 // PushDeclContext because we don't have a scope.
1850 ContextRAII SavedContext(*this, Instantiation);
1851 EnterExpressionEvaluationContext EvalContext(*this,
1852 Sema::PotentiallyEvaluated);
1854 // If this is an instantiation of a local class, merge this local
1855 // instantiation scope with the enclosing scope. Otherwise, every
1856 // instantiation of a class has its own local instantiation scope.
1857 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1858 LocalInstantiationScope Scope(*this, MergeWithParentScope);
1860 // Pull attributes from the pattern onto the instantiation.
1861 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1863 // Start the definition of this instantiation.
1864 Instantiation->startDefinition();
1866 Instantiation->setTagKind(Pattern->getTagKind());
1868 // Do substitution on the base class specifiers.
1869 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
1872 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
1873 SmallVector<Decl*, 4> Fields;
1874 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
1875 FieldsWithMemberInitializers;
1876 // Delay instantiation of late parsed attributes.
1877 LateInstantiatedAttrVec LateAttrs;
1878 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1880 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1881 MemberEnd = Pattern->decls_end();
1882 Member != MemberEnd; ++Member) {
1883 // Don't instantiate members not belonging in this semantic context.
1886 // template <int i> class A {
1890 // 'class B' has the template as lexical context but semantically it is
1891 // introduced in namespace scope.
1892 if ((*Member)->getDeclContext() != Pattern)
1895 if ((*Member)->isInvalidDecl()) {
1900 Decl *NewMember = Instantiator.Visit(*Member);
1902 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
1903 Fields.push_back(Field);
1904 FieldDecl *OldField = cast<FieldDecl>(*Member);
1905 if (OldField->getInClassInitializer())
1906 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1908 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1909 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1910 // specialization causes the implicit instantiation of the definitions
1911 // of unscoped member enumerations.
1912 // Record a point of instantiation for this implicit instantiation.
1913 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1914 Enum->isCompleteDefinition()) {
1915 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
1916 assert(MSInfo && "no spec info for member enum specialization");
1917 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
1918 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1922 if (NewMember->isInvalidDecl())
1925 // FIXME: Eventually, a NULL return will mean that one of the
1926 // instantiations was a semantic disaster, and we'll want to set Invalid =
1927 // true. For now, we expect to skip some members that we can't yet handle.
1931 // Finish checking fields.
1932 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
1933 SourceLocation(), SourceLocation(), 0);
1934 CheckCompletedCXXClass(Instantiation);
1936 // Attach any in-class member initializers now the class is complete.
1938 // C++11 [expr.prim.general]p4:
1939 // Otherwise, if a member-declarator declares a non-static data member
1940 // (9.2) of a class X, the expression this is a prvalue of type "pointer
1941 // to X" within the optional brace-or-equal-initializer. It shall not
1942 // appear elsewhere in the member-declarator.
1943 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
1945 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1946 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1947 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1948 Expr *OldInit = OldField->getInClassInitializer();
1950 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
1951 /*CXXDirectInit=*/false);
1952 if (NewInit.isInvalid())
1953 NewField->setInvalidDecl();
1955 Expr *Init = NewInit.take();
1956 assert(Init && "no-argument initializer in class");
1957 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
1958 ActOnCXXInClassMemberInitializer(NewField,
1959 Init->getSourceRange().getBegin(),
1964 // Instantiate late parsed attributes, and attach them to their decls.
1965 // See Sema::InstantiateAttrs
1966 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
1967 E = LateAttrs.end(); I != E; ++I) {
1968 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
1969 CurrentInstantiationScope = I->Scope;
1971 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
1972 I->NewDecl->addAttr(NewAttr);
1973 LocalInstantiationScope::deleteScopes(I->Scope,
1974 Instantiator.getStartingScope());
1976 Instantiator.disableLateAttributeInstantiation();
1979 if (!FieldsWithMemberInitializers.empty())
1980 ActOnFinishDelayedMemberInitializers(Instantiation);
1982 if (TSK == TSK_ImplicitInstantiation) {
1983 Instantiation->setLocation(Pattern->getLocation());
1984 Instantiation->setLocStart(Pattern->getInnerLocStart());
1985 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
1988 if (Instantiation->isInvalidDecl())
1991 // Instantiate any out-of-line class template partial
1992 // specializations now.
1993 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1994 P = Instantiator.delayed_partial_spec_begin(),
1995 PEnd = Instantiator.delayed_partial_spec_end();
1997 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2006 // Exit the scope of this instantiation.
2010 Consumer.HandleTagDeclDefinition(Instantiation);
2012 // Always emit the vtable for an explicit instantiation definition
2013 // of a polymorphic class template specialization.
2014 if (TSK == TSK_ExplicitInstantiationDefinition)
2015 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2021 /// \brief Instantiate the definition of an enum from a given pattern.
2023 /// \param PointOfInstantiation The point of instantiation within the
2025 /// \param Instantiation is the declaration whose definition is being
2026 /// instantiated. This will be a member enumeration of a class
2027 /// temploid specialization, or a local enumeration within a
2028 /// function temploid specialization.
2029 /// \param Pattern The templated declaration from which the instantiation
2031 /// \param TemplateArgs The template arguments to be substituted into
2033 /// \param TSK The kind of implicit or explicit instantiation to perform.
2035 /// \return \c true if an error occurred, \c false otherwise.
2036 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2037 EnumDecl *Instantiation, EnumDecl *Pattern,
2038 const MultiLevelTemplateArgumentList &TemplateArgs,
2039 TemplateSpecializationKind TSK) {
2040 EnumDecl *PatternDef = Pattern->getDefinition();
2041 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2042 Instantiation->getInstantiatedFromMemberEnum(),
2043 Pattern, PatternDef, TSK,/*Complain*/true))
2045 Pattern = PatternDef;
2047 // Record the point of instantiation.
2048 if (MemberSpecializationInfo *MSInfo
2049 = Instantiation->getMemberSpecializationInfo()) {
2050 MSInfo->setTemplateSpecializationKind(TSK);
2051 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2054 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2058 // Enter the scope of this instantiation. We don't use
2059 // PushDeclContext because we don't have a scope.
2060 ContextRAII SavedContext(*this, Instantiation);
2061 EnterExpressionEvaluationContext EvalContext(*this,
2062 Sema::PotentiallyEvaluated);
2064 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2066 // Pull attributes from the pattern onto the instantiation.
2067 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2069 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2070 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2072 // Exit the scope of this instantiation.
2075 return Instantiation->isInvalidDecl();
2079 /// \brief A partial specialization whose template arguments have matched
2080 /// a given template-id.
2081 struct PartialSpecMatchResult {
2082 ClassTemplatePartialSpecializationDecl *Partial;
2083 TemplateArgumentList *Args;
2088 Sema::InstantiateClassTemplateSpecialization(
2089 SourceLocation PointOfInstantiation,
2090 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2091 TemplateSpecializationKind TSK,
2093 // Perform the actual instantiation on the canonical declaration.
2094 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2095 ClassTemplateSpec->getCanonicalDecl());
2097 // Check whether we have already instantiated or specialized this class
2098 // template specialization.
2099 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2100 if (ClassTemplateSpec->getSpecializationKind() ==
2101 TSK_ExplicitInstantiationDeclaration &&
2102 TSK == TSK_ExplicitInstantiationDefinition) {
2103 // An explicit instantiation definition follows an explicit instantiation
2104 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2105 // explicit instantiation.
2106 ClassTemplateSpec->setSpecializationKind(TSK);
2108 // If this is an explicit instantiation definition, mark the
2110 if (TSK == TSK_ExplicitInstantiationDefinition &&
2111 !ClassTemplateSpec->isInvalidDecl())
2112 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2117 // We can only instantiate something that hasn't already been
2118 // instantiated or specialized. Fail without any diagnostics: our
2119 // caller will provide an error message.
2123 if (ClassTemplateSpec->isInvalidDecl())
2126 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2127 CXXRecordDecl *Pattern = 0;
2129 // C++ [temp.class.spec.match]p1:
2130 // When a class template is used in a context that requires an
2131 // instantiation of the class, it is necessary to determine
2132 // whether the instantiation is to be generated using the primary
2133 // template or one of the partial specializations. This is done by
2134 // matching the template arguments of the class template
2135 // specialization with the template argument lists of the partial
2137 typedef PartialSpecMatchResult MatchResult;
2138 SmallVector<MatchResult, 4> Matched;
2139 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2140 Template->getPartialSpecializations(PartialSpecs);
2141 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2142 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2143 TemplateDeductionInfo Info(Context, PointOfInstantiation);
2144 if (TemplateDeductionResult Result
2145 = DeduceTemplateArguments(Partial,
2146 ClassTemplateSpec->getTemplateArgs(),
2148 // FIXME: Store the failed-deduction information for use in
2149 // diagnostics, later.
2152 Matched.push_back(PartialSpecMatchResult());
2153 Matched.back().Partial = Partial;
2154 Matched.back().Args = Info.take();
2158 // If we're dealing with a member template where the template parameters
2159 // have been instantiated, this provides the original template parameters
2160 // from which the member template's parameters were instantiated.
2161 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
2163 if (Matched.size() >= 1) {
2164 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2165 if (Matched.size() == 1) {
2166 // -- If exactly one matching specialization is found, the
2167 // instantiation is generated from that specialization.
2168 // We don't need to do anything for this.
2170 // -- If more than one matching specialization is found, the
2171 // partial order rules (14.5.4.2) are used to determine
2172 // whether one of the specializations is more specialized
2173 // than the others. If none of the specializations is more
2174 // specialized than all of the other matching
2175 // specializations, then the use of the class template is
2176 // ambiguous and the program is ill-formed.
2177 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2178 PEnd = Matched.end();
2180 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2181 PointOfInstantiation)
2186 // Determine if the best partial specialization is more specialized than
2188 bool Ambiguous = false;
2189 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2190 PEnd = Matched.end();
2193 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2194 PointOfInstantiation)
2202 // Partial ordering did not produce a clear winner. Complain.
2203 ClassTemplateSpec->setInvalidDecl();
2204 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2205 << ClassTemplateSpec;
2207 // Print the matching partial specializations.
2208 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2209 PEnd = Matched.end();
2211 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2212 << getTemplateArgumentBindingsText(
2213 P->Partial->getTemplateParameters(),
2220 // Instantiate using the best class template partial specialization.
2221 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2222 while (OrigPartialSpec->getInstantiatedFromMember()) {
2223 // If we've found an explicit specialization of this class template,
2224 // stop here and use that as the pattern.
2225 if (OrigPartialSpec->isMemberSpecialization())
2228 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2231 Pattern = OrigPartialSpec;
2232 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2234 // -- If no matches are found, the instantiation is generated
2235 // from the primary template.
2236 ClassTemplateDecl *OrigTemplate = Template;
2237 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2238 // If we've found an explicit specialization of this class template,
2239 // stop here and use that as the pattern.
2240 if (OrigTemplate->isMemberSpecialization())
2243 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2246 Pattern = OrigTemplate->getTemplatedDecl();
2249 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2251 getTemplateInstantiationArgs(ClassTemplateSpec),
2258 /// \brief Instantiates the definitions of all of the member
2259 /// of the given class, which is an instantiation of a class template
2260 /// or a member class of a template.
2262 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2263 CXXRecordDecl *Instantiation,
2264 const MultiLevelTemplateArgumentList &TemplateArgs,
2265 TemplateSpecializationKind TSK) {
2266 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2267 DEnd = Instantiation->decls_end();
2269 bool SuppressNew = false;
2270 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
2271 if (FunctionDecl *Pattern
2272 = Function->getInstantiatedFromMemberFunction()) {
2273 MemberSpecializationInfo *MSInfo
2274 = Function->getMemberSpecializationInfo();
2275 assert(MSInfo && "No member specialization information?");
2276 if (MSInfo->getTemplateSpecializationKind()
2277 == TSK_ExplicitSpecialization)
2280 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2282 MSInfo->getTemplateSpecializationKind(),
2283 MSInfo->getPointOfInstantiation(),
2288 if (Function->isDefined())
2291 if (TSK == TSK_ExplicitInstantiationDefinition) {
2292 // C++0x [temp.explicit]p8:
2293 // An explicit instantiation definition that names a class template
2294 // specialization explicitly instantiates the class template
2295 // specialization and is only an explicit instantiation definition
2296 // of members whose definition is visible at the point of
2298 if (!Pattern->isDefined())
2301 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2303 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2305 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2308 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
2309 if (Var->isStaticDataMember()) {
2310 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2311 assert(MSInfo && "No member specialization information?");
2312 if (MSInfo->getTemplateSpecializationKind()
2313 == TSK_ExplicitSpecialization)
2316 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2318 MSInfo->getTemplateSpecializationKind(),
2319 MSInfo->getPointOfInstantiation(),
2324 if (TSK == TSK_ExplicitInstantiationDefinition) {
2325 // C++0x [temp.explicit]p8:
2326 // An explicit instantiation definition that names a class template
2327 // specialization explicitly instantiates the class template
2328 // specialization and is only an explicit instantiation definition
2329 // of members whose definition is visible at the point of
2331 if (!Var->getInstantiatedFromStaticDataMember()
2332 ->getOutOfLineDefinition())
2335 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2336 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2338 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2341 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
2342 // Always skip the injected-class-name, along with any
2343 // redeclarations of nested classes, since both would cause us
2344 // to try to instantiate the members of a class twice.
2345 if (Record->isInjectedClassName() || Record->getPreviousDecl())
2348 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2349 assert(MSInfo && "No member specialization information?");
2351 if (MSInfo->getTemplateSpecializationKind()
2352 == TSK_ExplicitSpecialization)
2355 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2357 MSInfo->getTemplateSpecializationKind(),
2358 MSInfo->getPointOfInstantiation(),
2363 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2364 assert(Pattern && "Missing instantiated-from-template information");
2366 if (!Record->getDefinition()) {
2367 if (!Pattern->getDefinition()) {
2368 // C++0x [temp.explicit]p8:
2369 // An explicit instantiation definition that names a class template
2370 // specialization explicitly instantiates the class template
2371 // specialization and is only an explicit instantiation definition
2372 // of members whose definition is visible at the point of
2374 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2375 MSInfo->setTemplateSpecializationKind(TSK);
2376 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2382 InstantiateClass(PointOfInstantiation, Record, Pattern,
2386 if (TSK == TSK_ExplicitInstantiationDefinition &&
2387 Record->getTemplateSpecializationKind() ==
2388 TSK_ExplicitInstantiationDeclaration) {
2389 Record->setTemplateSpecializationKind(TSK);
2390 MarkVTableUsed(PointOfInstantiation, Record, true);
2394 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2396 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2398 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2399 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2400 assert(MSInfo && "No member specialization information?");
2402 if (MSInfo->getTemplateSpecializationKind()
2403 == TSK_ExplicitSpecialization)
2406 if (CheckSpecializationInstantiationRedecl(
2407 PointOfInstantiation, TSK, Enum,
2408 MSInfo->getTemplateSpecializationKind(),
2409 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2413 if (Enum->getDefinition())
2416 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2417 assert(Pattern && "Missing instantiated-from-template information");
2419 if (TSK == TSK_ExplicitInstantiationDefinition) {
2420 if (!Pattern->getDefinition())
2423 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2425 MSInfo->setTemplateSpecializationKind(TSK);
2426 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2432 /// \brief Instantiate the definitions of all of the members of the
2433 /// given class template specialization, which was named as part of an
2434 /// explicit instantiation.
2436 Sema::InstantiateClassTemplateSpecializationMembers(
2437 SourceLocation PointOfInstantiation,
2438 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2439 TemplateSpecializationKind TSK) {
2440 // C++0x [temp.explicit]p7:
2441 // An explicit instantiation that names a class template
2442 // specialization is an explicit instantion of the same kind
2443 // (declaration or definition) of each of its members (not
2444 // including members inherited from base classes) that has not
2445 // been previously explicitly specialized in the translation unit
2446 // containing the explicit instantiation, except as described
2448 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2449 getTemplateInstantiationArgs(ClassTemplateSpec),
2454 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2458 TemplateInstantiator Instantiator(*this, TemplateArgs,
2461 return Instantiator.TransformStmt(S);
2465 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2469 TemplateInstantiator Instantiator(*this, TemplateArgs,
2472 return Instantiator.TransformExpr(E);
2475 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2476 const MultiLevelTemplateArgumentList &TemplateArgs,
2477 SmallVectorImpl<Expr *> &Outputs) {
2481 TemplateInstantiator Instantiator(*this, TemplateArgs,
2484 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2487 NestedNameSpecifierLoc
2488 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2489 const MultiLevelTemplateArgumentList &TemplateArgs) {
2491 return NestedNameSpecifierLoc();
2493 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2495 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2498 /// \brief Do template substitution on declaration name info.
2500 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2501 const MultiLevelTemplateArgumentList &TemplateArgs) {
2502 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2503 NameInfo.getName());
2504 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2508 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2509 TemplateName Name, SourceLocation Loc,
2510 const MultiLevelTemplateArgumentList &TemplateArgs) {
2511 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2514 SS.Adopt(QualifierLoc);
2515 return Instantiator.TransformTemplateName(SS, Name, Loc);
2518 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2519 TemplateArgumentListInfo &Result,
2520 const MultiLevelTemplateArgumentList &TemplateArgs) {
2521 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2524 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2527 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2528 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2529 for (LocalInstantiationScope *Current = this; Current;
2530 Current = Current->Outer) {
2532 // Check if we found something within this scope.
2533 const Decl *CheckD = D;
2535 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2536 if (Found != Current->LocalDecls.end())
2537 return &Found->second;
2539 // If this is a tag declaration, it's possible that we need to look for
2540 // a previous declaration.
2541 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2542 CheckD = Tag->getPreviousDecl();
2547 // If we aren't combined with our outer scope, we're done.
2548 if (!Current->CombineWithOuterScope)
2552 // If we didn't find the decl, then we either have a sema bug, or we have a
2553 // forward reference to a label declaration. Return null to indicate that
2554 // we have an uninstantiated label.
2555 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2559 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2560 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2561 if (Stored.isNull())
2563 else if (Stored.is<Decl *>()) {
2564 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2567 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
2570 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2572 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2573 Pack->push_back(Inst);
2576 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2577 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2578 assert(Stored.isNull() && "Already instantiated this local");
2579 DeclArgumentPack *Pack = new DeclArgumentPack;
2581 ArgumentPacks.push_back(Pack);
2584 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2585 const TemplateArgument *ExplicitArgs,
2586 unsigned NumExplicitArgs) {
2587 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2588 "Already have a partially-substituted pack");
2589 assert((!PartiallySubstitutedPack
2590 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2591 "Wrong number of arguments in partially-substituted pack");
2592 PartiallySubstitutedPack = Pack;
2593 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2594 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2597 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2598 const TemplateArgument **ExplicitArgs,
2599 unsigned *NumExplicitArgs) const {
2602 if (NumExplicitArgs)
2603 *NumExplicitArgs = 0;
2605 for (const LocalInstantiationScope *Current = this; Current;
2606 Current = Current->Outer) {
2607 if (Current->PartiallySubstitutedPack) {
2609 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2610 if (NumExplicitArgs)
2611 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2613 return Current->PartiallySubstitutedPack;
2616 if (!Current->CombineWithOuterScope)