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 //===----------------------------------------------------------------------===/
14 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/Parse/DeclSpec.h"
21 #include "clang/Basic/LangOptions.h"
23 using namespace clang;
25 //===----------------------------------------------------------------------===/
26 // Template Instantiation Support
27 //===----------------------------------------------------------------------===/
29 /// \brief Retrieve the template argument list(s) that should be used to
30 /// instantiate the definition of the given declaration.
32 /// \param D the declaration for which we are computing template instantiation
35 /// \param Innermost if non-NULL, the innermost template argument list.
37 /// \param RelativeToPrimary true if we should get the template
38 /// arguments relative to the primary template, even when we're
39 /// dealing with a specialization. This is only relevant for function
40 /// template specializations.
41 MultiLevelTemplateArgumentList
42 Sema::getTemplateInstantiationArgs(NamedDecl *D,
43 const TemplateArgumentList *Innermost,
44 bool RelativeToPrimary) {
45 // Accumulate the set of template argument lists in this structure.
46 MultiLevelTemplateArgumentList Result;
49 Result.addOuterTemplateArguments(Innermost);
51 DeclContext *Ctx = dyn_cast<DeclContext>(D);
53 Ctx = D->getDeclContext();
55 while (!Ctx->isFileContext()) {
56 // Add template arguments from a class template instantiation.
57 if (ClassTemplateSpecializationDecl *Spec
58 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
59 // We're done when we hit an explicit specialization.
60 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization)
63 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
65 // If this class template specialization was instantiated from a
66 // specialized member that is a class template, we're done.
67 assert(Spec->getSpecializedTemplate() && "No class template?");
68 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
71 // Add template arguments from a function template specialization.
72 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
73 if (!RelativeToPrimary &&
74 Function->getTemplateSpecializationKind()
75 == TSK_ExplicitSpecialization)
78 if (const TemplateArgumentList *TemplateArgs
79 = Function->getTemplateSpecializationArgs()) {
80 // Add the template arguments for this specialization.
81 Result.addOuterTemplateArguments(TemplateArgs);
83 // If this function was instantiated from a specialized member that is
84 // a function template, we're done.
85 assert(Function->getPrimaryTemplate() && "No function template?");
86 if (Function->getPrimaryTemplate()->isMemberSpecialization())
90 // If this is a friend declaration and it declares an entity at
91 // namespace scope, take arguments from its lexical parent
92 // instead of its semantic parent.
93 if (Function->getFriendObjectKind() &&
94 Function->getDeclContext()->isFileContext()) {
95 Ctx = Function->getLexicalDeclContext();
96 RelativeToPrimary = false;
101 Ctx = Ctx->getParent();
102 RelativeToPrimary = false;
108 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
110 case TemplateInstantiation:
111 case DefaultTemplateArgumentInstantiation:
112 case DefaultFunctionArgumentInstantiation:
115 case ExplicitTemplateArgumentSubstitution:
116 case DeducedTemplateArgumentSubstitution:
117 case PriorTemplateArgumentSubstitution:
118 case DefaultTemplateArgumentChecking:
125 Sema::InstantiatingTemplate::
126 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
128 SourceRange InstantiationRange)
131 Invalid = CheckInstantiationDepth(PointOfInstantiation,
134 ActiveTemplateInstantiation Inst;
135 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
136 Inst.PointOfInstantiation = PointOfInstantiation;
137 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
138 Inst.TemplateArgs = 0;
139 Inst.NumTemplateArgs = 0;
140 Inst.InstantiationRange = InstantiationRange;
141 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
145 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
146 SourceLocation PointOfInstantiation,
147 TemplateDecl *Template,
148 const TemplateArgument *TemplateArgs,
149 unsigned NumTemplateArgs,
150 SourceRange InstantiationRange)
153 Invalid = CheckInstantiationDepth(PointOfInstantiation,
156 ActiveTemplateInstantiation Inst;
158 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
159 Inst.PointOfInstantiation = PointOfInstantiation;
160 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
161 Inst.TemplateArgs = TemplateArgs;
162 Inst.NumTemplateArgs = NumTemplateArgs;
163 Inst.InstantiationRange = InstantiationRange;
164 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
168 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
169 SourceLocation PointOfInstantiation,
170 FunctionTemplateDecl *FunctionTemplate,
171 const TemplateArgument *TemplateArgs,
172 unsigned NumTemplateArgs,
173 ActiveTemplateInstantiation::InstantiationKind Kind,
174 SourceRange InstantiationRange)
177 Invalid = CheckInstantiationDepth(PointOfInstantiation,
180 ActiveTemplateInstantiation Inst;
182 Inst.PointOfInstantiation = PointOfInstantiation;
183 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
184 Inst.TemplateArgs = TemplateArgs;
185 Inst.NumTemplateArgs = NumTemplateArgs;
186 Inst.InstantiationRange = InstantiationRange;
187 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
189 if (!Inst.isInstantiationRecord())
190 ++SemaRef.NonInstantiationEntries;
194 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
195 SourceLocation PointOfInstantiation,
196 ClassTemplatePartialSpecializationDecl *PartialSpec,
197 const TemplateArgument *TemplateArgs,
198 unsigned NumTemplateArgs,
199 SourceRange InstantiationRange)
204 ActiveTemplateInstantiation Inst;
205 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
206 Inst.PointOfInstantiation = PointOfInstantiation;
207 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
208 Inst.TemplateArgs = TemplateArgs;
209 Inst.NumTemplateArgs = NumTemplateArgs;
210 Inst.InstantiationRange = InstantiationRange;
211 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
213 assert(!Inst.isInstantiationRecord());
214 ++SemaRef.NonInstantiationEntries;
217 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
218 SourceLocation PointOfInstantiation,
220 const TemplateArgument *TemplateArgs,
221 unsigned NumTemplateArgs,
222 SourceRange InstantiationRange)
225 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
228 ActiveTemplateInstantiation Inst;
230 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
231 Inst.PointOfInstantiation = PointOfInstantiation;
232 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
233 Inst.TemplateArgs = TemplateArgs;
234 Inst.NumTemplateArgs = NumTemplateArgs;
235 Inst.InstantiationRange = InstantiationRange;
236 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
240 Sema::InstantiatingTemplate::
241 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
242 TemplateDecl *Template,
243 NonTypeTemplateParmDecl *Param,
244 const TemplateArgument *TemplateArgs,
245 unsigned NumTemplateArgs,
246 SourceRange InstantiationRange) : SemaRef(SemaRef) {
249 ActiveTemplateInstantiation Inst;
250 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
251 Inst.PointOfInstantiation = PointOfInstantiation;
252 Inst.Template = Template;
253 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
254 Inst.TemplateArgs = TemplateArgs;
255 Inst.NumTemplateArgs = NumTemplateArgs;
256 Inst.InstantiationRange = InstantiationRange;
257 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
259 assert(!Inst.isInstantiationRecord());
260 ++SemaRef.NonInstantiationEntries;
263 Sema::InstantiatingTemplate::
264 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
265 TemplateDecl *Template,
266 TemplateTemplateParmDecl *Param,
267 const TemplateArgument *TemplateArgs,
268 unsigned NumTemplateArgs,
269 SourceRange InstantiationRange) : SemaRef(SemaRef) {
271 ActiveTemplateInstantiation Inst;
272 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
273 Inst.PointOfInstantiation = PointOfInstantiation;
274 Inst.Template = Template;
275 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
276 Inst.TemplateArgs = TemplateArgs;
277 Inst.NumTemplateArgs = NumTemplateArgs;
278 Inst.InstantiationRange = InstantiationRange;
279 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
281 assert(!Inst.isInstantiationRecord());
282 ++SemaRef.NonInstantiationEntries;
285 Sema::InstantiatingTemplate::
286 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
287 TemplateDecl *Template,
289 const TemplateArgument *TemplateArgs,
290 unsigned NumTemplateArgs,
291 SourceRange InstantiationRange) : SemaRef(SemaRef) {
294 ActiveTemplateInstantiation Inst;
295 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
296 Inst.PointOfInstantiation = PointOfInstantiation;
297 Inst.Template = Template;
298 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
299 Inst.TemplateArgs = TemplateArgs;
300 Inst.NumTemplateArgs = NumTemplateArgs;
301 Inst.InstantiationRange = InstantiationRange;
302 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
304 assert(!Inst.isInstantiationRecord());
305 ++SemaRef.NonInstantiationEntries;
308 void Sema::InstantiatingTemplate::Clear() {
310 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
311 assert(SemaRef.NonInstantiationEntries > 0);
312 --SemaRef.NonInstantiationEntries;
315 SemaRef.ActiveTemplateInstantiations.pop_back();
320 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
321 SourceLocation PointOfInstantiation,
322 SourceRange InstantiationRange) {
323 assert(SemaRef.NonInstantiationEntries <=
324 SemaRef.ActiveTemplateInstantiations.size());
325 if ((SemaRef.ActiveTemplateInstantiations.size() -
326 SemaRef.NonInstantiationEntries)
327 <= SemaRef.getLangOptions().InstantiationDepth)
330 SemaRef.Diag(PointOfInstantiation,
331 diag::err_template_recursion_depth_exceeded)
332 << SemaRef.getLangOptions().InstantiationDepth
333 << InstantiationRange;
334 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
335 << SemaRef.getLangOptions().InstantiationDepth;
339 /// \brief Prints the current instantiation stack through a series of
341 void Sema::PrintInstantiationStack() {
342 // FIXME: In all of these cases, we need to show the template arguments
343 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
344 Active = ActiveTemplateInstantiations.rbegin(),
345 ActiveEnd = ActiveTemplateInstantiations.rend();
348 switch (Active->Kind) {
349 case ActiveTemplateInstantiation::TemplateInstantiation: {
350 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
351 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
352 unsigned DiagID = diag::note_template_member_class_here;
353 if (isa<ClassTemplateSpecializationDecl>(Record))
354 DiagID = diag::note_template_class_instantiation_here;
355 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
357 << Context.getTypeDeclType(Record)
358 << Active->InstantiationRange;
359 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
361 if (Function->getPrimaryTemplate())
362 DiagID = diag::note_function_template_spec_here;
364 DiagID = diag::note_template_member_function_here;
365 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
368 << Active->InstantiationRange;
370 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
371 diag::note_template_static_data_member_def_here)
373 << Active->InstantiationRange;
378 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
379 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
380 std::string TemplateArgsStr
381 = TemplateSpecializationType::PrintTemplateArgumentList(
382 Active->TemplateArgs,
383 Active->NumTemplateArgs,
384 Context.PrintingPolicy);
385 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
386 diag::note_default_arg_instantiation_here)
387 << (Template->getNameAsString() + TemplateArgsStr)
388 << Active->InstantiationRange;
392 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
393 FunctionTemplateDecl *FnTmpl
394 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
395 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
396 diag::note_explicit_template_arg_substitution_here)
397 << FnTmpl << Active->InstantiationRange;
401 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
402 if (ClassTemplatePartialSpecializationDecl *PartialSpec
403 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
404 (Decl *)Active->Entity)) {
405 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
406 diag::note_partial_spec_deduct_instantiation_here)
407 << Context.getTypeDeclType(PartialSpec)
408 << Active->InstantiationRange;
410 FunctionTemplateDecl *FnTmpl
411 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
412 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
413 diag::note_function_template_deduction_instantiation_here)
414 << FnTmpl << Active->InstantiationRange;
418 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
419 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
420 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
422 std::string TemplateArgsStr
423 = TemplateSpecializationType::PrintTemplateArgumentList(
424 Active->TemplateArgs,
425 Active->NumTemplateArgs,
426 Context.PrintingPolicy);
427 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
428 diag::note_default_function_arg_instantiation_here)
429 << (FD->getNameAsString() + TemplateArgsStr)
430 << Active->InstantiationRange;
434 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
435 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
437 if (!Parm->getName().empty())
438 Name = std::string(" '") + Parm->getName().str() + "'";
440 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
441 diag::note_prior_template_arg_substitution)
442 << isa<TemplateTemplateParmDecl>(Parm)
444 << getTemplateArgumentBindingsText(
445 Active->Template->getTemplateParameters(),
446 Active->TemplateArgs,
447 Active->NumTemplateArgs)
448 << Active->InstantiationRange;
452 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
453 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
454 diag::note_template_default_arg_checking)
455 << getTemplateArgumentBindingsText(
456 Active->Template->getTemplateParameters(),
457 Active->TemplateArgs,
458 Active->NumTemplateArgs)
459 << Active->InstantiationRange;
466 bool Sema::isSFINAEContext() const {
467 using llvm::SmallVector;
468 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
469 Active = ActiveTemplateInstantiations.rbegin(),
470 ActiveEnd = ActiveTemplateInstantiations.rend();
474 switch(Active->Kind) {
475 case ActiveTemplateInstantiation::TemplateInstantiation:
476 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
477 // This is a template instantiation, so there is no SFINAE.
480 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
481 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
482 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
483 // A default template argument instantiation and substitution into
484 // template parameters with arguments for prior parameters may or may
485 // not be a SFINAE context; look further up the stack.
488 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
489 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
490 // We're either substitution explicitly-specified template arguments
491 // or deduced template arguments, so SFINAE applies.
499 //===----------------------------------------------------------------------===/
500 // Template Instantiation for Types
501 //===----------------------------------------------------------------------===/
503 class TemplateInstantiator
504 : public TreeTransform<TemplateInstantiator> {
505 const MultiLevelTemplateArgumentList &TemplateArgs;
507 DeclarationName Entity;
510 typedef TreeTransform<TemplateInstantiator> inherited;
512 TemplateInstantiator(Sema &SemaRef,
513 const MultiLevelTemplateArgumentList &TemplateArgs,
515 DeclarationName Entity)
516 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
519 /// \brief Determine whether the given type \p T has already been
522 /// For the purposes of template instantiation, a type has already been
523 /// transformed if it is NULL or if it is not dependent.
524 bool AlreadyTransformed(QualType T) {
525 return T.isNull() || !T->isDependentType();
528 /// \brief Returns the location of the entity being instantiated, if known.
529 SourceLocation getBaseLocation() { return Loc; }
531 /// \brief Returns the name of the entity being instantiated, if any.
532 DeclarationName getBaseEntity() { return Entity; }
534 /// \brief Sets the "base" location and entity when that
535 /// information is known based on another transformation.
536 void setBase(SourceLocation Loc, DeclarationName Entity) {
538 this->Entity = Entity;
541 /// \brief Transform the given declaration by instantiating a reference to
542 /// this declaration.
543 Decl *TransformDecl(Decl *D);
545 /// \brief Transform the definition of the given declaration by
546 /// instantiating it.
547 Decl *TransformDefinition(Decl *D);
549 /// \bried Transform the first qualifier within a scope by instantiating the
551 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
553 /// \brief Rebuild the exception declaration and register the declaration
554 /// as an instantiated local.
555 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T,
556 TypeSourceInfo *Declarator,
557 IdentifierInfo *Name,
558 SourceLocation Loc, SourceRange TypeRange);
560 /// \brief Check for tag mismatches when instantiating an
562 QualType RebuildElaboratedType(QualType T, ElaboratedType::TagKind Tag);
564 Sema::OwningExprResult TransformPredefinedExpr(PredefinedExpr *E);
565 Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E);
566 Sema::OwningExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
567 Sema::OwningExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
568 NonTypeTemplateParmDecl *D);
570 /// \brief Transforms a template type parameter type by performing
571 /// substitution of the corresponding template type argument.
572 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
573 TemplateTypeParmTypeLoc TL);
577 Decl *TemplateInstantiator::TransformDecl(Decl *D) {
581 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
582 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
583 // If the corresponding template argument is NULL or non-existent, it's
584 // because we are performing instantiation from explicitly-specified
585 // template arguments in a function template, but there were some
586 // arguments left unspecified.
587 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
591 TemplateName Template
592 = TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsTemplate();
593 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
594 "Wrong kind of template template argument");
595 return Template.getAsTemplateDecl();
598 // Fall through to find the instantiated declaration for this template
599 // template parameter.
602 return SemaRef.FindInstantiatedDecl(cast<NamedDecl>(D), TemplateArgs);
605 Decl *TemplateInstantiator::TransformDefinition(Decl *D) {
606 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
610 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
615 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
616 SourceLocation Loc) {
617 // If the first part of the nested-name-specifier was a template type
618 // parameter, instantiate that type parameter down to a tag type.
619 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
620 const TemplateTypeParmType *TTP
621 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
622 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
623 QualType T = TemplateArgs(TTP->getDepth(), TTP->getIndex()).getAsType();
625 return cast_or_null<NamedDecl>(TransformDecl(D));
627 if (const TagType *Tag = T->getAs<TagType>())
628 return Tag->getDecl();
630 // The resulting type is not a tag; complain.
631 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
636 return cast_or_null<NamedDecl>(TransformDecl(D));
640 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
642 TypeSourceInfo *Declarator,
643 IdentifierInfo *Name,
645 SourceRange TypeRange) {
646 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator,
647 Name, Loc, TypeRange);
648 if (Var && !Var->isInvalidDecl())
649 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
654 TemplateInstantiator::RebuildElaboratedType(QualType T,
655 ElaboratedType::TagKind Tag) {
656 if (const TagType *TT = T->getAs<TagType>()) {
657 TagDecl* TD = TT->getDecl();
659 // FIXME: this location is very wrong; we really need typelocs.
660 SourceLocation TagLocation = TD->getTagKeywordLoc();
662 // FIXME: type might be anonymous.
663 IdentifierInfo *Id = TD->getIdentifier();
665 // TODO: should we even warn on struct/class mismatches for this? Seems
666 // like it's likely to produce a lot of spurious errors.
667 if (!SemaRef.isAcceptableTagRedeclaration(TD, Tag, TagLocation, *Id)) {
668 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
670 << CodeModificationHint::CreateReplacement(SourceRange(TagLocation),
672 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
676 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(T, Tag);
679 Sema::OwningExprResult
680 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
681 if (!E->isTypeDependent())
682 return SemaRef.Owned(E->Retain());
684 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
685 assert(currentDecl && "Must have current function declaration when "
688 PredefinedExpr::IdentType IT = E->getIdentType();
690 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
692 llvm::APInt LengthI(32, Length + 1);
693 QualType ResTy = getSema().Context.CharTy.withConst();
694 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
695 ArrayType::Normal, 0);
697 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
698 return getSema().Owned(PE);
701 Sema::OwningExprResult
702 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
703 NonTypeTemplateParmDecl *NTTP) {
704 // If the corresponding template argument is NULL or non-existent, it's
705 // because we are performing instantiation from explicitly-specified
706 // template arguments in a function template, but there were some
707 // arguments left unspecified.
708 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
709 NTTP->getPosition()))
710 return SemaRef.Owned(E->Retain());
712 const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(),
713 NTTP->getPosition());
715 // The template argument itself might be an expression, in which
716 // case we just return that expression.
717 if (Arg.getKind() == TemplateArgument::Expression)
718 return SemaRef.Owned(Arg.getAsExpr()->Retain());
720 if (Arg.getKind() == TemplateArgument::Declaration) {
721 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
723 // Find the instantiation of the template argument. This is
724 // required for nested templates.
725 VD = cast_or_null<ValueDecl>(
726 getSema().FindInstantiatedDecl(VD, TemplateArgs));
728 return SemaRef.ExprError();
730 // Derive the type we want the substituted decl to have. This had
731 // better be non-dependent, or these checks will have serious problems.
732 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
735 assert(!TargetType.isNull() && "type substitution failed for param type");
736 assert(!TargetType->isDependentType() && "param type still dependent");
738 if (VD->getDeclContext()->isRecord() &&
739 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
740 // If the value is a class member, we might have a pointer-to-member.
741 // Determine whether the non-type template template parameter is of
742 // pointer-to-member type. If so, we need to build an appropriate
743 // expression for a pointer-to-member, since a "normal" DeclRefExpr
744 // would refer to the member itself.
745 if (TargetType->isMemberPointerType()) {
747 = SemaRef.Context.getTypeDeclType(
748 cast<RecordDecl>(VD->getDeclContext()));
749 NestedNameSpecifier *Qualifier
750 = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
751 ClassType.getTypePtr());
753 SS.setScopeRep(Qualifier);
754 OwningExprResult RefExpr
755 = SemaRef.BuildDeclRefExpr(VD,
756 VD->getType().getNonReferenceType(),
759 if (RefExpr.isInvalid())
760 return SemaRef.ExprError();
762 RefExpr = SemaRef.CreateBuiltinUnaryOp(E->getLocation(),
763 UnaryOperator::AddrOf,
765 assert(!RefExpr.isInvalid() &&
766 SemaRef.Context.hasSameType(((Expr*) RefExpr.get())->getType(),
768 return move(RefExpr);
772 QualType T = VD->getType().getNonReferenceType();
774 if (TargetType->isPointerType()) {
775 // C++03 [temp.arg.nontype]p5:
776 // - For a non-type template-parameter of type pointer to
777 // object, qualification conversions and the array-to-pointer
778 // conversion are applied.
779 // - For a non-type template-parameter of type pointer to
780 // function, only the function-to-pointer conversion is
783 OwningExprResult RefExpr
784 = SemaRef.BuildDeclRefExpr(VD, T, E->getLocation());
785 if (RefExpr.isInvalid())
786 return SemaRef.ExprError();
788 // Decay functions and arrays.
789 Expr *RefE = (Expr *)RefExpr.get();
790 SemaRef.DefaultFunctionArrayConversion(RefE);
791 if (RefE != RefExpr.get()) {
793 RefExpr = SemaRef.Owned(RefE);
796 // Qualification conversions.
798 SemaRef.ImpCastExprToType(RefE, TargetType.getUnqualifiedType(),
800 return SemaRef.Owned(RefE);
803 // If the non-type template parameter has reference type, qualify the
804 // resulting declaration reference with the extra qualifiers on the
805 // type that the reference refers to.
806 if (const ReferenceType *TargetRef = TargetType->getAs<ReferenceType>())
807 T = SemaRef.Context.getQualifiedType(T,
808 TargetRef->getPointeeType().getQualifiers());
810 return SemaRef.BuildDeclRefExpr(VD, T, E->getLocation());
813 assert(Arg.getKind() == TemplateArgument::Integral);
814 QualType T = Arg.getIntegralType();
815 if (T->isCharType() || T->isWideCharType())
816 return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
817 Arg.getAsIntegral()->getZExtValue(),
820 E->getSourceRange().getBegin()));
821 if (T->isBooleanType())
822 return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
823 Arg.getAsIntegral()->getBoolValue(),
825 E->getSourceRange().getBegin()));
827 assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T));
828 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
829 *Arg.getAsIntegral(),
831 E->getSourceRange().getBegin()));
835 Sema::OwningExprResult
836 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
837 NamedDecl *D = E->getDecl();
838 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
839 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
840 return TransformTemplateParmRefExpr(E, NTTP);
842 // We have a non-type template parameter that isn't fully substituted;
843 // FindInstantiatedDecl will find it in the local instantiation scope.
846 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
849 Sema::OwningExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
850 CXXDefaultArgExpr *E) {
851 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
852 getDescribedFunctionTemplate() &&
853 "Default arg expressions are never formed in dependent cases.");
854 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
855 cast<FunctionDecl>(E->getParam()->getDeclContext()),
861 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
862 TemplateTypeParmTypeLoc TL) {
863 TemplateTypeParmType *T = TL.getTypePtr();
864 if (T->getDepth() < TemplateArgs.getNumLevels()) {
865 // Replace the template type parameter with its corresponding
866 // template argument.
868 // If the corresponding template argument is NULL or doesn't exist, it's
869 // because we are performing instantiation from explicitly-specified
870 // template arguments in a function template class, but there were some
871 // arguments left unspecified.
872 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
873 TemplateTypeParmTypeLoc NewTL
874 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
875 NewTL.setNameLoc(TL.getNameLoc());
879 assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind()
880 == TemplateArgument::Type &&
881 "Template argument kind mismatch");
884 = TemplateArgs(T->getDepth(), T->getIndex()).getAsType();
886 // TODO: only do this uniquing once, at the start of instantiation.
888 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
889 SubstTemplateTypeParmTypeLoc NewTL
890 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
891 NewTL.setNameLoc(TL.getNameLoc());
895 // The template type parameter comes from an inner template (e.g.,
896 // the template parameter list of a member template inside the
897 // template we are instantiating). Create a new template type
898 // parameter with the template "level" reduced by one.
900 = getSema().Context.getTemplateTypeParmType(T->getDepth()
901 - TemplateArgs.getNumLevels(),
903 T->isParameterPack(),
905 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
906 NewTL.setNameLoc(TL.getNameLoc());
910 /// \brief Perform substitution on the type T with a given set of template
913 /// This routine substitutes the given template arguments into the
914 /// type T and produces the instantiated type.
916 /// \param T the type into which the template arguments will be
917 /// substituted. If this type is not dependent, it will be returned
920 /// \param TemplateArgs the template arguments that will be
921 /// substituted for the top-level template parameters within T.
923 /// \param Loc the location in the source code where this substitution
924 /// is being performed. It will typically be the location of the
925 /// declarator (if we're instantiating the type of some declaration)
926 /// or the location of the type in the source code (if, e.g., we're
927 /// instantiating the type of a cast expression).
929 /// \param Entity the name of the entity associated with a declaration
930 /// being instantiated (if any). May be empty to indicate that there
931 /// is no such entity (if, e.g., this is a type that occurs as part of
932 /// a cast expression) or that the entity has no name (e.g., an
933 /// unnamed function parameter).
935 /// \returns If the instantiation succeeds, the instantiated
936 /// type. Otherwise, produces diagnostics and returns a NULL type.
937 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
938 const MultiLevelTemplateArgumentList &Args,
940 DeclarationName Entity) {
941 assert(!ActiveTemplateInstantiations.empty() &&
942 "Cannot perform an instantiation without some context on the "
943 "instantiation stack");
945 if (!T->getType()->isDependentType())
948 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
949 return Instantiator.TransformType(T);
952 /// Deprecated form of the above.
953 QualType Sema::SubstType(QualType T,
954 const MultiLevelTemplateArgumentList &TemplateArgs,
955 SourceLocation Loc, DeclarationName Entity) {
956 assert(!ActiveTemplateInstantiations.empty() &&
957 "Cannot perform an instantiation without some context on the "
958 "instantiation stack");
960 // If T is not a dependent type, there is nothing to do.
961 if (!T->isDependentType())
964 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
965 return Instantiator.TransformType(T);
968 /// \brief Perform substitution on the base class specifiers of the
969 /// given class template specialization.
971 /// Produces a diagnostic and returns true on error, returns false and
972 /// attaches the instantiated base classes to the class template
973 /// specialization if successful.
975 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
976 CXXRecordDecl *Pattern,
977 const MultiLevelTemplateArgumentList &TemplateArgs) {
978 bool Invalid = false;
979 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
980 for (ClassTemplateSpecializationDecl::base_class_iterator
981 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
982 Base != BaseEnd; ++Base) {
983 if (!Base->getType()->isDependentType()) {
984 const CXXRecordDecl *BaseDecl =
985 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
987 // Make sure to set the attributes from the base.
988 SetClassDeclAttributesFromBase(Instantiation, BaseDecl,
991 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
995 QualType BaseType = SubstType(Base->getType(),
997 Base->getSourceRange().getBegin(),
999 if (BaseType.isNull()) {
1004 if (CXXBaseSpecifier *InstantiatedBase
1005 = CheckBaseSpecifier(Instantiation,
1006 Base->getSourceRange(),
1008 Base->getAccessSpecifierAsWritten(),
1010 /*FIXME: Not totally accurate */
1011 Base->getSourceRange().getBegin()))
1012 InstantiatedBases.push_back(InstantiatedBase);
1018 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1019 InstantiatedBases.size()))
1025 /// \brief Instantiate the definition of a class from a given pattern.
1027 /// \param PointOfInstantiation The point of instantiation within the
1030 /// \param Instantiation is the declaration whose definition is being
1031 /// instantiated. This will be either a class template specialization
1032 /// or a member class of a class template specialization.
1034 /// \param Pattern is the pattern from which the instantiation
1035 /// occurs. This will be either the declaration of a class template or
1036 /// the declaration of a member class of a class template.
1038 /// \param TemplateArgs The template arguments to be substituted into
1041 /// \param TSK the kind of implicit or explicit instantiation to perform.
1043 /// \param Complain whether to complain if the class cannot be instantiated due
1044 /// to the lack of a definition.
1046 /// \returns true if an error occurred, false otherwise.
1048 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1049 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1050 const MultiLevelTemplateArgumentList &TemplateArgs,
1051 TemplateSpecializationKind TSK,
1053 bool Invalid = false;
1055 CXXRecordDecl *PatternDef
1056 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1060 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
1061 Diag(PointOfInstantiation,
1062 diag::err_implicit_instantiate_member_undefined)
1063 << Context.getTypeDeclType(Instantiation);
1064 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1066 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1067 << (TSK != TSK_ImplicitInstantiation)
1068 << Context.getTypeDeclType(Instantiation);
1069 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1073 Pattern = PatternDef;
1075 // \brief Record the point of instantiation.
1076 if (MemberSpecializationInfo *MSInfo
1077 = Instantiation->getMemberSpecializationInfo()) {
1078 MSInfo->setTemplateSpecializationKind(TSK);
1079 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1080 } else if (ClassTemplateSpecializationDecl *Spec
1081 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1082 Spec->setTemplateSpecializationKind(TSK);
1083 Spec->setPointOfInstantiation(PointOfInstantiation);
1086 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1090 // Enter the scope of this instantiation. We don't use
1091 // PushDeclContext because we don't have a scope.
1092 DeclContext *PreviousContext = CurContext;
1093 CurContext = Instantiation;
1095 // Start the definition of this instantiation.
1096 Instantiation->startDefinition();
1098 // Do substitution on the base class specifiers.
1099 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
1102 llvm::SmallVector<DeclPtrTy, 4> Fields;
1103 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1104 MemberEnd = Pattern->decls_end();
1105 Member != MemberEnd; ++Member) {
1106 Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs);
1108 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
1109 Fields.push_back(DeclPtrTy::make(Field));
1110 else if (NewMember->isInvalidDecl())
1113 // FIXME: Eventually, a NULL return will mean that one of the
1114 // instantiations was a semantic disaster, and we'll want to set Invalid =
1115 // true. For now, we expect to skip some members that we can't yet handle.
1119 // Finish checking fields.
1120 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
1121 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
1123 CheckCompletedCXXClass(Instantiation);
1124 if (Instantiation->isInvalidDecl())
1127 // Exit the scope of this instantiation.
1128 CurContext = PreviousContext;
1130 // If this is a polymorphic C++ class without a key function, we'll
1131 // have to mark all of the virtual members to allow emission of a vtable
1132 // in this translation unit.
1133 if (Instantiation->isDynamicClass() &&
1134 !Context.getKeyFunction(Instantiation)) {
1135 // Local classes need to have their methods instantiated immediately in
1136 // order to have the correct instantiation scope.
1137 if (Instantiation->isLocalClass()) {
1138 MarkVirtualMembersReferenced(PointOfInstantiation,
1141 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Instantiation,
1142 PointOfInstantiation));
1147 Consumer.HandleTagDeclDefinition(Instantiation);
1153 Sema::InstantiateClassTemplateSpecialization(
1154 SourceLocation PointOfInstantiation,
1155 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1156 TemplateSpecializationKind TSK,
1158 // Perform the actual instantiation on the canonical declaration.
1159 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
1160 ClassTemplateSpec->getCanonicalDecl());
1162 // Check whether we have already instantiated or specialized this class
1163 // template specialization.
1164 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1165 if (ClassTemplateSpec->getSpecializationKind() ==
1166 TSK_ExplicitInstantiationDeclaration &&
1167 TSK == TSK_ExplicitInstantiationDefinition) {
1168 // An explicit instantiation definition follows an explicit instantiation
1169 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1170 // explicit instantiation.
1171 ClassTemplateSpec->setSpecializationKind(TSK);
1175 // We can only instantiate something that hasn't already been
1176 // instantiated or specialized. Fail without any diagnostics: our
1177 // caller will provide an error message.
1181 if (ClassTemplateSpec->isInvalidDecl())
1184 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
1185 CXXRecordDecl *Pattern = 0;
1187 // C++ [temp.class.spec.match]p1:
1188 // When a class template is used in a context that requires an
1189 // instantiation of the class, it is necessary to determine
1190 // whether the instantiation is to be generated using the primary
1191 // template or one of the partial specializations. This is done by
1192 // matching the template arguments of the class template
1193 // specialization with the template argument lists of the partial
1195 typedef std::pair<ClassTemplatePartialSpecializationDecl *,
1196 TemplateArgumentList *> MatchResult;
1197 llvm::SmallVector<MatchResult, 4> Matched;
1198 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
1199 Partial = Template->getPartialSpecializations().begin(),
1200 PartialEnd = Template->getPartialSpecializations().end();
1201 Partial != PartialEnd;
1203 TemplateDeductionInfo Info(Context, PointOfInstantiation);
1204 if (TemplateDeductionResult Result
1205 = DeduceTemplateArguments(&*Partial,
1206 ClassTemplateSpec->getTemplateArgs(),
1208 // FIXME: Store the failed-deduction information for use in
1209 // diagnostics, later.
1212 Matched.push_back(std::make_pair(&*Partial, Info.take()));
1216 if (Matched.size() >= 1) {
1217 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
1218 if (Matched.size() == 1) {
1219 // -- If exactly one matching specialization is found, the
1220 // instantiation is generated from that specialization.
1221 // We don't need to do anything for this.
1223 // -- If more than one matching specialization is found, the
1224 // partial order rules (14.5.4.2) are used to determine
1225 // whether one of the specializations is more specialized
1226 // than the others. If none of the specializations is more
1227 // specialized than all of the other matching
1228 // specializations, then the use of the class template is
1229 // ambiguous and the program is ill-formed.
1230 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1231 PEnd = Matched.end();
1233 if (getMoreSpecializedPartialSpecialization(P->first, Best->first,
1234 PointOfInstantiation)
1239 // Determine if the best partial specialization is more specialized than
1241 bool Ambiguous = false;
1242 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1243 PEnd = Matched.end();
1246 getMoreSpecializedPartialSpecialization(P->first, Best->first,
1247 PointOfInstantiation)
1255 // Partial ordering did not produce a clear winner. Complain.
1256 ClassTemplateSpec->setInvalidDecl();
1257 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
1258 << ClassTemplateSpec;
1260 // Print the matching partial specializations.
1261 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1262 PEnd = Matched.end();
1264 Diag(P->first->getLocation(), diag::note_partial_spec_match)
1265 << getTemplateArgumentBindingsText(P->first->getTemplateParameters(),
1272 // Instantiate using the best class template partial specialization.
1273 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->first;
1274 while (OrigPartialSpec->getInstantiatedFromMember()) {
1275 // If we've found an explicit specialization of this class template,
1276 // stop here and use that as the pattern.
1277 if (OrigPartialSpec->isMemberSpecialization())
1280 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
1283 Pattern = OrigPartialSpec;
1284 ClassTemplateSpec->setInstantiationOf(Best->first, Best->second);
1286 // -- If no matches are found, the instantiation is generated
1287 // from the primary template.
1288 ClassTemplateDecl *OrigTemplate = Template;
1289 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
1290 // If we've found an explicit specialization of this class template,
1291 // stop here and use that as the pattern.
1292 if (OrigTemplate->isMemberSpecialization())
1295 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
1298 Pattern = OrigTemplate->getTemplatedDecl();
1301 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
1303 getTemplateInstantiationArgs(ClassTemplateSpec),
1307 for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
1308 // FIXME: Implement TemplateArgumentList::Destroy!
1309 // if (Matched[I].first != Pattern)
1310 // Matched[I].second->Destroy(Context);
1316 /// \brief Instantiates the definitions of all of the member
1317 /// of the given class, which is an instantiation of a class template
1318 /// or a member class of a template.
1320 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1321 CXXRecordDecl *Instantiation,
1322 const MultiLevelTemplateArgumentList &TemplateArgs,
1323 TemplateSpecializationKind TSK) {
1324 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1325 DEnd = Instantiation->decls_end();
1327 bool SuppressNew = false;
1328 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1329 if (FunctionDecl *Pattern
1330 = Function->getInstantiatedFromMemberFunction()) {
1331 MemberSpecializationInfo *MSInfo
1332 = Function->getMemberSpecializationInfo();
1333 assert(MSInfo && "No member specialization information?");
1334 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1336 MSInfo->getTemplateSpecializationKind(),
1337 MSInfo->getPointOfInstantiation(),
1342 if (Function->getBody())
1345 if (TSK == TSK_ExplicitInstantiationDefinition) {
1346 // C++0x [temp.explicit]p8:
1347 // An explicit instantiation definition that names a class template
1348 // specialization explicitly instantiates the class template
1349 // specialization and is only an explicit instantiation definition
1350 // of members whose definition is visible at the point of
1352 if (!Pattern->getBody())
1355 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1357 InstantiateFunctionDefinition(PointOfInstantiation, Function);
1359 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1362 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1363 if (Var->isStaticDataMember()) {
1364 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
1365 assert(MSInfo && "No member specialization information?");
1366 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1368 MSInfo->getTemplateSpecializationKind(),
1369 MSInfo->getPointOfInstantiation(),
1374 if (TSK == TSK_ExplicitInstantiationDefinition) {
1375 // C++0x [temp.explicit]p8:
1376 // An explicit instantiation definition that names a class template
1377 // specialization explicitly instantiates the class template
1378 // specialization and is only an explicit instantiation definition
1379 // of members whose definition is visible at the point of
1381 if (!Var->getInstantiatedFromStaticDataMember()
1382 ->getOutOfLineDefinition())
1385 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1386 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
1388 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1391 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1392 if (Record->isInjectedClassName())
1395 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
1396 assert(MSInfo && "No member specialization information?");
1397 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1399 MSInfo->getTemplateSpecializationKind(),
1400 MSInfo->getPointOfInstantiation(),
1405 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
1406 assert(Pattern && "Missing instantiated-from-template information");
1408 if (!Record->getDefinition()) {
1409 if (!Pattern->getDefinition()) {
1410 // C++0x [temp.explicit]p8:
1411 // An explicit instantiation definition that names a class template
1412 // specialization explicitly instantiates the class template
1413 // specialization and is only an explicit instantiation definition
1414 // of members whose definition is visible at the point of
1416 if (TSK == TSK_ExplicitInstantiationDeclaration) {
1417 MSInfo->setTemplateSpecializationKind(TSK);
1418 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1424 InstantiateClass(PointOfInstantiation, Record, Pattern,
1429 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
1431 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
1437 /// \brief Instantiate the definitions of all of the members of the
1438 /// given class template specialization, which was named as part of an
1439 /// explicit instantiation.
1441 Sema::InstantiateClassTemplateSpecializationMembers(
1442 SourceLocation PointOfInstantiation,
1443 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1444 TemplateSpecializationKind TSK) {
1445 // C++0x [temp.explicit]p7:
1446 // An explicit instantiation that names a class template
1447 // specialization is an explicit instantion of the same kind
1448 // (declaration or definition) of each of its members (not
1449 // including members inherited from base classes) that has not
1450 // been previously explicitly specialized in the translation unit
1451 // containing the explicit instantiation, except as described
1453 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1454 getTemplateInstantiationArgs(ClassTemplateSpec),
1458 Sema::OwningStmtResult
1459 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
1463 TemplateInstantiator Instantiator(*this, TemplateArgs,
1466 return Instantiator.TransformStmt(S);
1469 Sema::OwningExprResult
1470 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
1474 TemplateInstantiator Instantiator(*this, TemplateArgs,
1477 return Instantiator.TransformExpr(E);
1480 /// \brief Do template substitution on a nested-name-specifier.
1481 NestedNameSpecifier *
1482 Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS,
1484 const MultiLevelTemplateArgumentList &TemplateArgs) {
1485 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
1487 return Instantiator.TransformNestedNameSpecifier(NNS, Range);
1491 Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc,
1492 const MultiLevelTemplateArgumentList &TemplateArgs) {
1493 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1495 return Instantiator.TransformTemplateName(Name);
1498 bool Sema::Subst(const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
1499 const MultiLevelTemplateArgumentList &TemplateArgs) {
1500 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
1503 return Instantiator.TransformTemplateArgument(Input, Output);