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"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Parse/DeclSpec.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "llvm/Support/Compiler.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.
31 MultiLevelTemplateArgumentList
32 Sema::getTemplateInstantiationArgs(NamedDecl *D) {
33 // Accumulate the set of template argument lists in this structure.
34 MultiLevelTemplateArgumentList Result;
36 DeclContext *Ctx = dyn_cast<DeclContext>(D);
38 Ctx = D->getDeclContext();
40 while (!Ctx->isFileContext()) {
41 // Add template arguments from a class template instantiation.
42 if (ClassTemplateSpecializationDecl *Spec
43 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
44 // We're done when we hit an explicit specialization.
45 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization)
48 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
50 // If this class template specialization was instantiated from a
51 // specialized member that is a class template, we're done.
52 assert(Spec->getSpecializedTemplate() && "No class template?");
53 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
56 // Add template arguments from a function template specialization.
57 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
58 if (Function->getTemplateSpecializationKind()
59 == TSK_ExplicitSpecialization)
62 if (const TemplateArgumentList *TemplateArgs
63 = Function->getTemplateSpecializationArgs()) {
64 // Add the template arguments for this specialization.
65 Result.addOuterTemplateArguments(TemplateArgs);
67 // If this function was instantiated from a specialized member that is
68 // a function template, we're done.
69 assert(Function->getPrimaryTemplate() && "No function template?");
70 if (Function->getPrimaryTemplate()->isMemberSpecialization())
74 // If this is a friend declaration and it declares an entity at
75 // namespace scope, take arguments from its lexical parent
76 // instead of its semantic parent.
77 if (Function->getFriendObjectKind() &&
78 Function->getDeclContext()->isFileContext()) {
79 Ctx = Function->getLexicalDeclContext();
84 Ctx = Ctx->getParent();
90 Sema::InstantiatingTemplate::
91 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
93 SourceRange InstantiationRange)
96 Invalid = CheckInstantiationDepth(PointOfInstantiation,
99 ActiveTemplateInstantiation Inst;
100 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
101 Inst.PointOfInstantiation = PointOfInstantiation;
102 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
103 Inst.TemplateArgs = 0;
104 Inst.NumTemplateArgs = 0;
105 Inst.InstantiationRange = InstantiationRange;
106 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
111 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
112 SourceLocation PointOfInstantiation,
113 TemplateDecl *Template,
114 const TemplateArgument *TemplateArgs,
115 unsigned NumTemplateArgs,
116 SourceRange InstantiationRange)
119 Invalid = CheckInstantiationDepth(PointOfInstantiation,
122 ActiveTemplateInstantiation Inst;
124 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
125 Inst.PointOfInstantiation = PointOfInstantiation;
126 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
127 Inst.TemplateArgs = TemplateArgs;
128 Inst.NumTemplateArgs = NumTemplateArgs;
129 Inst.InstantiationRange = InstantiationRange;
130 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
135 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
136 SourceLocation PointOfInstantiation,
137 FunctionTemplateDecl *FunctionTemplate,
138 const TemplateArgument *TemplateArgs,
139 unsigned NumTemplateArgs,
140 ActiveTemplateInstantiation::InstantiationKind Kind,
141 SourceRange InstantiationRange)
144 Invalid = CheckInstantiationDepth(PointOfInstantiation,
147 ActiveTemplateInstantiation Inst;
149 Inst.PointOfInstantiation = PointOfInstantiation;
150 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
151 Inst.TemplateArgs = TemplateArgs;
152 Inst.NumTemplateArgs = NumTemplateArgs;
153 Inst.InstantiationRange = InstantiationRange;
154 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
159 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
160 SourceLocation PointOfInstantiation,
161 ClassTemplatePartialSpecializationDecl *PartialSpec,
162 const TemplateArgument *TemplateArgs,
163 unsigned NumTemplateArgs,
164 SourceRange InstantiationRange)
167 Invalid = CheckInstantiationDepth(PointOfInstantiation,
170 ActiveTemplateInstantiation Inst;
172 = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
173 Inst.PointOfInstantiation = PointOfInstantiation;
174 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
175 Inst.TemplateArgs = TemplateArgs;
176 Inst.NumTemplateArgs = NumTemplateArgs;
177 Inst.InstantiationRange = InstantiationRange;
178 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
183 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
184 SourceLocation PointOfInstantation,
186 const TemplateArgument *TemplateArgs,
187 unsigned NumTemplateArgs,
188 SourceRange InstantiationRange)
191 Invalid = CheckInstantiationDepth(PointOfInstantation, InstantiationRange);
194 ActiveTemplateInstantiation Inst;
196 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
197 Inst.PointOfInstantiation = PointOfInstantation;
198 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
199 Inst.TemplateArgs = TemplateArgs;
200 Inst.NumTemplateArgs = NumTemplateArgs;
201 Inst.InstantiationRange = InstantiationRange;
202 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
207 void Sema::InstantiatingTemplate::Clear() {
209 SemaRef.ActiveTemplateInstantiations.pop_back();
214 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
215 SourceLocation PointOfInstantiation,
216 SourceRange InstantiationRange) {
217 if (SemaRef.ActiveTemplateInstantiations.size()
218 <= SemaRef.getLangOptions().InstantiationDepth)
221 SemaRef.Diag(PointOfInstantiation,
222 diag::err_template_recursion_depth_exceeded)
223 << SemaRef.getLangOptions().InstantiationDepth
224 << InstantiationRange;
225 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
226 << SemaRef.getLangOptions().InstantiationDepth;
230 /// \brief Prints the current instantiation stack through a series of
232 void Sema::PrintInstantiationStack() {
233 // FIXME: In all of these cases, we need to show the template arguments
234 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
235 Active = ActiveTemplateInstantiations.rbegin(),
236 ActiveEnd = ActiveTemplateInstantiations.rend();
239 switch (Active->Kind) {
240 case ActiveTemplateInstantiation::TemplateInstantiation: {
241 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
242 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
243 unsigned DiagID = diag::note_template_member_class_here;
244 if (isa<ClassTemplateSpecializationDecl>(Record))
245 DiagID = diag::note_template_class_instantiation_here;
246 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
248 << Context.getTypeDeclType(Record)
249 << Active->InstantiationRange;
250 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
252 if (Function->getPrimaryTemplate())
253 DiagID = diag::note_function_template_spec_here;
255 DiagID = diag::note_template_member_function_here;
256 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
259 << Active->InstantiationRange;
261 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
262 diag::note_template_static_data_member_def_here)
264 << Active->InstantiationRange;
269 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
270 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
271 std::string TemplateArgsStr
272 = TemplateSpecializationType::PrintTemplateArgumentList(
273 Active->TemplateArgs,
274 Active->NumTemplateArgs,
275 Context.PrintingPolicy);
276 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
277 diag::note_default_arg_instantiation_here)
278 << (Template->getNameAsString() + TemplateArgsStr)
279 << Active->InstantiationRange;
283 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
284 FunctionTemplateDecl *FnTmpl
285 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
286 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
287 diag::note_explicit_template_arg_substitution_here)
288 << FnTmpl << Active->InstantiationRange;
292 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
293 if (ClassTemplatePartialSpecializationDecl *PartialSpec
294 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
295 (Decl *)Active->Entity)) {
296 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
297 diag::note_partial_spec_deduct_instantiation_here)
298 << Context.getTypeDeclType(PartialSpec)
299 << Active->InstantiationRange;
301 FunctionTemplateDecl *FnTmpl
302 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
303 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
304 diag::note_function_template_deduction_instantiation_here)
305 << FnTmpl << Active->InstantiationRange;
309 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
310 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
311 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
313 std::string TemplateArgsStr
314 = TemplateSpecializationType::PrintTemplateArgumentList(
315 Active->TemplateArgs,
316 Active->NumTemplateArgs,
317 Context.PrintingPolicy);
318 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
319 diag::note_default_function_arg_instantiation_here)
320 << (FD->getNameAsString() + TemplateArgsStr)
321 << Active->InstantiationRange;
329 bool Sema::isSFINAEContext() const {
330 using llvm::SmallVector;
331 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
332 Active = ActiveTemplateInstantiations.rbegin(),
333 ActiveEnd = ActiveTemplateInstantiations.rend();
337 switch(Active->Kind) {
338 case ActiveTemplateInstantiation::TemplateInstantiation:
339 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
341 // This is a template instantiation, so there is no SFINAE.
344 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
345 // A default template argument instantiation may or may not be a
346 // SFINAE context; look further up the stack.
349 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
350 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
351 // We're either substitution explicitly-specified template arguments
352 // or deduced template arguments, so SFINAE applies.
360 //===----------------------------------------------------------------------===/
361 // Template Instantiation for Types
362 //===----------------------------------------------------------------------===/
364 class VISIBILITY_HIDDEN TemplateInstantiator
365 : public TreeTransform<TemplateInstantiator> {
366 const MultiLevelTemplateArgumentList &TemplateArgs;
368 DeclarationName Entity;
371 typedef TreeTransform<TemplateInstantiator> inherited;
373 TemplateInstantiator(Sema &SemaRef,
374 const MultiLevelTemplateArgumentList &TemplateArgs,
376 DeclarationName Entity)
377 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
380 /// \brief Determine whether the given type \p T has already been
383 /// For the purposes of template instantiation, a type has already been
384 /// transformed if it is NULL or if it is not dependent.
385 bool AlreadyTransformed(QualType T) {
386 return T.isNull() || !T->isDependentType();
389 /// \brief Returns the location of the entity being instantiated, if known.
390 SourceLocation getBaseLocation() { return Loc; }
392 /// \brief Returns the name of the entity being instantiated, if any.
393 DeclarationName getBaseEntity() { return Entity; }
395 /// \brief Sets the "base" location and entity when that
396 /// information is known based on another transformation.
397 void setBase(SourceLocation Loc, DeclarationName Entity) {
399 this->Entity = Entity;
402 /// \brief Transform the given declaration by instantiating a reference to
403 /// this declaration.
404 Decl *TransformDecl(Decl *D);
406 /// \brief Transform the definition of the given declaration by
407 /// instantiating it.
408 Decl *TransformDefinition(Decl *D);
410 /// \bried Transform the first qualifier within a scope by instantiating the
412 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
414 /// \brief Rebuild the exception declaration and register the declaration
415 /// as an instantiated local.
416 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T,
417 DeclaratorInfo *Declarator,
418 IdentifierInfo *Name,
419 SourceLocation Loc, SourceRange TypeRange);
421 /// \brief Check for tag mismatches when instantiating an
423 QualType RebuildElaboratedType(QualType T, ElaboratedType::TagKind Tag);
425 Sema::OwningExprResult TransformPredefinedExpr(PredefinedExpr *E,
426 bool isAddressOfOperand);
427 Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E,
428 bool isAddressOfOperand);
430 /// \brief Transforms a template type parameter type by performing
431 /// substitution of the corresponding template type argument.
432 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
433 TemplateTypeParmTypeLoc TL);
437 Decl *TemplateInstantiator::TransformDecl(Decl *D) {
441 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
442 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
443 assert(TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsDecl() &&
444 "Wrong kind of template template argument");
445 return cast<TemplateDecl>(TemplateArgs(TTP->getDepth(),
446 TTP->getPosition()).getAsDecl());
449 // If the corresponding template argument is NULL or non-existent, it's
450 // because we are performing instantiation from explicitly-specified
451 // template arguments in a function template, but there were some
452 // arguments left unspecified.
453 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
457 // FIXME: Implement depth reduction of template template parameters
459 "Reducing depth of template template parameters is not yet implemented");
462 return SemaRef.FindInstantiatedDecl(cast<NamedDecl>(D), TemplateArgs);
465 Decl *TemplateInstantiator::TransformDefinition(Decl *D) {
466 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
470 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
475 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
476 SourceLocation Loc) {
477 // If the first part of the nested-name-specifier was a template type
478 // parameter, instantiate that type parameter down to a tag type.
479 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
480 const TemplateTypeParmType *TTP
481 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
482 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
483 QualType T = TemplateArgs(TTP->getDepth(), TTP->getIndex()).getAsType();
485 return cast_or_null<NamedDecl>(TransformDecl(D));
487 if (const TagType *Tag = T->getAs<TagType>())
488 return Tag->getDecl();
490 // The resulting type is not a tag; complain.
491 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
496 return cast_or_null<NamedDecl>(TransformDecl(D));
500 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
502 DeclaratorInfo *Declarator,
503 IdentifierInfo *Name,
505 SourceRange TypeRange) {
506 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator,
507 Name, Loc, TypeRange);
508 if (Var && !Var->isInvalidDecl())
509 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
514 TemplateInstantiator::RebuildElaboratedType(QualType T,
515 ElaboratedType::TagKind Tag) {
516 if (const TagType *TT = T->getAs<TagType>()) {
517 TagDecl* TD = TT->getDecl();
519 // FIXME: this location is very wrong; we really need typelocs.
520 SourceLocation TagLocation = TD->getTagKeywordLoc();
522 // FIXME: type might be anonymous.
523 IdentifierInfo *Id = TD->getIdentifier();
525 // TODO: should we even warn on struct/class mismatches for this? Seems
526 // like it's likely to produce a lot of spurious errors.
527 if (!SemaRef.isAcceptableTagRedeclaration(TD, Tag, TagLocation, *Id)) {
528 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
530 << CodeModificationHint::CreateReplacement(SourceRange(TagLocation),
532 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
536 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(T, Tag);
539 Sema::OwningExprResult
540 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E,
541 bool isAddressOfOperand) {
542 if (!E->isTypeDependent())
543 return SemaRef.Owned(E->Retain());
545 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
546 assert(currentDecl && "Must have current function declaration when "
549 PredefinedExpr::IdentType IT = E->getIdentType();
552 PredefinedExpr::ComputeName(getSema().Context, IT, currentDecl).length();
554 llvm::APInt LengthI(32, Length + 1);
555 QualType ResTy = getSema().Context.CharTy.withConst();
556 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
557 ArrayType::Normal, 0);
559 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
560 return getSema().Owned(PE);
563 Sema::OwningExprResult
564 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E,
565 bool isAddressOfOperand) {
566 // FIXME: Clean this up a bit
567 NamedDecl *D = E->getDecl();
568 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
569 if (NTTP->getDepth() < TemplateArgs.getNumLevels()) {
571 // If the corresponding template argument is NULL or non-existent, it's
572 // because we are performing instantiation from explicitly-specified
573 // template arguments in a function template, but there were some
574 // arguments left unspecified.
575 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
576 NTTP->getPosition()))
577 return SemaRef.Owned(E->Retain());
579 const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(),
580 NTTP->getPosition());
582 // The template argument itself might be an expression, in which
583 // case we just return that expression.
584 if (Arg.getKind() == TemplateArgument::Expression)
585 return SemaRef.Owned(Arg.getAsExpr()->Retain());
587 if (Arg.getKind() == TemplateArgument::Declaration) {
588 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
590 VD = cast_or_null<ValueDecl>(
591 getSema().FindInstantiatedDecl(VD, TemplateArgs));
593 return SemaRef.ExprError();
595 return SemaRef.BuildDeclRefExpr(VD, VD->getType(), E->getLocation(),
596 /*FIXME:*/false, /*FIXME:*/false);
599 assert(Arg.getKind() == TemplateArgument::Integral);
600 QualType T = Arg.getIntegralType();
601 if (T->isCharType() || T->isWideCharType())
602 return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
603 Arg.getAsIntegral()->getZExtValue(),
606 E->getSourceRange().getBegin()));
607 if (T->isBooleanType())
608 return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
609 Arg.getAsIntegral()->getBoolValue(),
611 E->getSourceRange().getBegin()));
613 assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T));
614 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
615 *Arg.getAsIntegral(),
617 E->getSourceRange().getBegin()));
620 // We have a non-type template parameter that isn't fully substituted;
621 // FindInstantiatedDecl will find it in the local instantiation scope.
624 NamedDecl *InstD = SemaRef.FindInstantiatedDecl(D, TemplateArgs);
626 return SemaRef.ExprError();
628 // If we instantiated an UnresolvedUsingDecl and got back an UsingDecl,
629 // we need to get the underlying decl.
630 // FIXME: Is this correct? Maybe FindInstantiatedDecl should do this?
631 InstD = InstD->getUnderlyingDecl();
634 NestedNameSpecifier *Qualifier = 0;
635 if (E->getQualifier()) {
636 Qualifier = TransformNestedNameSpecifier(E->getQualifier(),
637 E->getQualifierRange());
639 return SemaRef.ExprError();
641 SS.setScopeRep(Qualifier);
642 SS.setRange(E->getQualifierRange());
645 return SemaRef.BuildDeclarationNameExpr(E->getLocation(), InstD,
652 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
653 TemplateTypeParmTypeLoc TL) {
654 TemplateTypeParmType *T = TL.getTypePtr();
655 if (T->getDepth() < TemplateArgs.getNumLevels()) {
656 // Replace the template type parameter with its corresponding
657 // template argument.
659 // If the corresponding template argument is NULL or doesn't exist, it's
660 // because we are performing instantiation from explicitly-specified
661 // template arguments in a function template class, but there were some
662 // arguments left unspecified.
663 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
664 TemplateTypeParmTypeLoc NewTL
665 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
666 NewTL.setNameLoc(TL.getNameLoc());
670 assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind()
671 == TemplateArgument::Type &&
672 "Template argument kind mismatch");
675 = TemplateArgs(T->getDepth(), T->getIndex()).getAsType();
677 // TODO: only do this uniquing once, at the start of instantiation.
679 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
680 SubstTemplateTypeParmTypeLoc NewTL
681 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
682 NewTL.setNameLoc(TL.getNameLoc());
686 // The template type parameter comes from an inner template (e.g.,
687 // the template parameter list of a member template inside the
688 // template we are instantiating). Create a new template type
689 // parameter with the template "level" reduced by one.
691 = getSema().Context.getTemplateTypeParmType(T->getDepth()
692 - TemplateArgs.getNumLevels(),
694 T->isParameterPack(),
696 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
697 NewTL.setNameLoc(TL.getNameLoc());
701 /// \brief Perform substitution on the type T with a given set of template
704 /// This routine substitutes the given template arguments into the
705 /// type T and produces the instantiated type.
707 /// \param T the type into which the template arguments will be
708 /// substituted. If this type is not dependent, it will be returned
711 /// \param TemplateArgs the template arguments that will be
712 /// substituted for the top-level template parameters within T.
714 /// \param Loc the location in the source code where this substitution
715 /// is being performed. It will typically be the location of the
716 /// declarator (if we're instantiating the type of some declaration)
717 /// or the location of the type in the source code (if, e.g., we're
718 /// instantiating the type of a cast expression).
720 /// \param Entity the name of the entity associated with a declaration
721 /// being instantiated (if any). May be empty to indicate that there
722 /// is no such entity (if, e.g., this is a type that occurs as part of
723 /// a cast expression) or that the entity has no name (e.g., an
724 /// unnamed function parameter).
726 /// \returns If the instantiation succeeds, the instantiated
727 /// type. Otherwise, produces diagnostics and returns a NULL type.
728 DeclaratorInfo *Sema::SubstType(DeclaratorInfo *T,
729 const MultiLevelTemplateArgumentList &Args,
731 DeclarationName Entity) {
732 assert(!ActiveTemplateInstantiations.empty() &&
733 "Cannot perform an instantiation without some context on the "
734 "instantiation stack");
736 if (!T->getType()->isDependentType())
739 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
740 return Instantiator.TransformType(T);
743 /// Deprecated form of the above.
744 QualType Sema::SubstType(QualType T,
745 const MultiLevelTemplateArgumentList &TemplateArgs,
746 SourceLocation Loc, DeclarationName Entity) {
747 assert(!ActiveTemplateInstantiations.empty() &&
748 "Cannot perform an instantiation without some context on the "
749 "instantiation stack");
751 // If T is not a dependent type, there is nothing to do.
752 if (!T->isDependentType())
755 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
756 return Instantiator.TransformType(T);
759 /// \brief Perform substitution on the base class specifiers of the
760 /// given class template specialization.
762 /// Produces a diagnostic and returns true on error, returns false and
763 /// attaches the instantiated base classes to the class template
764 /// specialization if successful.
766 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
767 CXXRecordDecl *Pattern,
768 const MultiLevelTemplateArgumentList &TemplateArgs) {
769 bool Invalid = false;
770 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
771 for (ClassTemplateSpecializationDecl::base_class_iterator
772 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
773 Base != BaseEnd; ++Base) {
774 if (!Base->getType()->isDependentType()) {
775 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
779 QualType BaseType = SubstType(Base->getType(),
781 Base->getSourceRange().getBegin(),
783 if (BaseType.isNull()) {
788 if (CXXBaseSpecifier *InstantiatedBase
789 = CheckBaseSpecifier(Instantiation,
790 Base->getSourceRange(),
792 Base->getAccessSpecifierAsWritten(),
794 /*FIXME: Not totally accurate */
795 Base->getSourceRange().getBegin()))
796 InstantiatedBases.push_back(InstantiatedBase);
802 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
803 InstantiatedBases.size()))
809 /// \brief Instantiate the definition of a class from a given pattern.
811 /// \param PointOfInstantiation The point of instantiation within the
814 /// \param Instantiation is the declaration whose definition is being
815 /// instantiated. This will be either a class template specialization
816 /// or a member class of a class template specialization.
818 /// \param Pattern is the pattern from which the instantiation
819 /// occurs. This will be either the declaration of a class template or
820 /// the declaration of a member class of a class template.
822 /// \param TemplateArgs The template arguments to be substituted into
825 /// \param TSK the kind of implicit or explicit instantiation to perform.
827 /// \param Complain whether to complain if the class cannot be instantiated due
828 /// to the lack of a definition.
830 /// \returns true if an error occurred, false otherwise.
832 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
833 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
834 const MultiLevelTemplateArgumentList &TemplateArgs,
835 TemplateSpecializationKind TSK,
837 bool Invalid = false;
839 CXXRecordDecl *PatternDef
840 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
844 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
845 Diag(PointOfInstantiation,
846 diag::err_implicit_instantiate_member_undefined)
847 << Context.getTypeDeclType(Instantiation);
848 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
850 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
851 << (TSK != TSK_ImplicitInstantiation)
852 << Context.getTypeDeclType(Instantiation);
853 Diag(Pattern->getLocation(), diag::note_template_decl_here);
857 Pattern = PatternDef;
859 // \brief Record the point of instantiation.
860 if (MemberSpecializationInfo *MSInfo
861 = Instantiation->getMemberSpecializationInfo()) {
862 MSInfo->setTemplateSpecializationKind(TSK);
863 MSInfo->setPointOfInstantiation(PointOfInstantiation);
864 } else if (ClassTemplateSpecializationDecl *Spec
865 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
866 Spec->setTemplateSpecializationKind(TSK);
867 Spec->setPointOfInstantiation(PointOfInstantiation);
870 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
874 // Enter the scope of this instantiation. We don't use
875 // PushDeclContext because we don't have a scope.
876 DeclContext *PreviousContext = CurContext;
877 CurContext = Instantiation;
879 // Start the definition of this instantiation.
880 Instantiation->startDefinition();
882 // Do substitution on the base class specifiers.
883 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
886 llvm::SmallVector<DeclPtrTy, 4> Fields;
887 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
888 MemberEnd = Pattern->decls_end();
889 Member != MemberEnd; ++Member) {
890 Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs);
892 if (NewMember->isInvalidDecl())
894 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
895 Fields.push_back(DeclPtrTy::make(Field));
896 else if (UsingDecl *UD = dyn_cast<UsingDecl>(NewMember))
897 Instantiation->addDecl(UD);
899 // FIXME: Eventually, a NULL return will mean that one of the
900 // instantiations was a semantic disaster, and we'll want to set Invalid =
901 // true. For now, we expect to skip some members that we can't yet handle.
905 // Finish checking fields.
906 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
907 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
909 if (Instantiation->isInvalidDecl())
912 // Add any implicitly-declared members that we might need.
914 AddImplicitlyDeclaredMembersToClass(Instantiation);
916 // Exit the scope of this instantiation.
917 CurContext = PreviousContext;
920 Consumer.HandleTagDeclDefinition(Instantiation);
926 Sema::InstantiateClassTemplateSpecialization(
927 SourceLocation PointOfInstantiation,
928 ClassTemplateSpecializationDecl *ClassTemplateSpec,
929 TemplateSpecializationKind TSK,
931 // Perform the actual instantiation on the canonical declaration.
932 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
933 ClassTemplateSpec->getCanonicalDecl());
935 // Check whether we have already instantiated or specialized this class
936 // template specialization.
937 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
938 if (ClassTemplateSpec->getSpecializationKind() ==
939 TSK_ExplicitInstantiationDeclaration &&
940 TSK == TSK_ExplicitInstantiationDefinition) {
941 // An explicit instantiation definition follows an explicit instantiation
942 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
943 // explicit instantiation.
944 ClassTemplateSpec->setSpecializationKind(TSK);
948 // We can only instantiate something that hasn't already been
949 // instantiated or specialized. Fail without any diagnostics: our
950 // caller will provide an error message.
954 if (ClassTemplateSpec->isInvalidDecl())
957 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
958 CXXRecordDecl *Pattern = 0;
960 // C++ [temp.class.spec.match]p1:
961 // When a class template is used in a context that requires an
962 // instantiation of the class, it is necessary to determine
963 // whether the instantiation is to be generated using the primary
964 // template or one of the partial specializations. This is done by
965 // matching the template arguments of the class template
966 // specialization with the template argument lists of the partial
968 typedef std::pair<ClassTemplatePartialSpecializationDecl *,
969 TemplateArgumentList *> MatchResult;
970 llvm::SmallVector<MatchResult, 4> Matched;
971 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
972 Partial = Template->getPartialSpecializations().begin(),
973 PartialEnd = Template->getPartialSpecializations().end();
974 Partial != PartialEnd;
976 TemplateDeductionInfo Info(Context);
977 if (TemplateDeductionResult Result
978 = DeduceTemplateArguments(&*Partial,
979 ClassTemplateSpec->getTemplateArgs(),
981 // FIXME: Store the failed-deduction information for use in
982 // diagnostics, later.
985 Matched.push_back(std::make_pair(&*Partial, Info.take()));
989 if (Matched.size() >= 1) {
990 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
991 if (Matched.size() == 1) {
992 // -- If exactly one matching specialization is found, the
993 // instantiation is generated from that specialization.
994 // We don't need to do anything for this.
996 // -- If more than one matching specialization is found, the
997 // partial order rules (14.5.4.2) are used to determine
998 // whether one of the specializations is more specialized
999 // than the others. If none of the specializations is more
1000 // specialized than all of the other matching
1001 // specializations, then the use of the class template is
1002 // ambiguous and the program is ill-formed.
1003 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1004 PEnd = Matched.end();
1006 if (getMoreSpecializedPartialSpecialization(P->first, Best->first)
1011 // Determine if the best partial specialization is more specialized than
1013 bool Ambiguous = false;
1014 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1015 PEnd = Matched.end();
1018 getMoreSpecializedPartialSpecialization(P->first, Best->first)
1026 // Partial ordering did not produce a clear winner. Complain.
1027 ClassTemplateSpec->setInvalidDecl();
1028 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
1029 << ClassTemplateSpec;
1031 // Print the matching partial specializations.
1032 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1033 PEnd = Matched.end();
1035 Diag(P->first->getLocation(), diag::note_partial_spec_match)
1036 << getTemplateArgumentBindingsText(P->first->getTemplateParameters(),
1043 // Instantiate using the best class template partial specialization.
1044 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->first;
1045 while (OrigPartialSpec->getInstantiatedFromMember()) {
1046 // If we've found an explicit specialization of this class template,
1047 // stop here and use that as the pattern.
1048 if (OrigPartialSpec->isMemberSpecialization())
1051 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
1054 Pattern = OrigPartialSpec;
1055 ClassTemplateSpec->setInstantiationOf(Best->first, Best->second);
1057 // -- If no matches are found, the instantiation is generated
1058 // from the primary template.
1059 ClassTemplateDecl *OrigTemplate = Template;
1060 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
1061 // If we've found an explicit specialization of this class template,
1062 // stop here and use that as the pattern.
1063 if (OrigTemplate->isMemberSpecialization())
1066 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
1069 Pattern = OrigTemplate->getTemplatedDecl();
1072 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
1074 getTemplateInstantiationArgs(ClassTemplateSpec),
1078 for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
1079 // FIXME: Implement TemplateArgumentList::Destroy!
1080 // if (Matched[I].first != Pattern)
1081 // Matched[I].second->Destroy(Context);
1087 /// \brief Instantiates the definitions of all of the member
1088 /// of the given class, which is an instantiation of a class template
1089 /// or a member class of a template.
1091 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1092 CXXRecordDecl *Instantiation,
1093 const MultiLevelTemplateArgumentList &TemplateArgs,
1094 TemplateSpecializationKind TSK) {
1095 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1096 DEnd = Instantiation->decls_end();
1098 bool SuppressNew = false;
1099 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1100 if (FunctionDecl *Pattern
1101 = Function->getInstantiatedFromMemberFunction()) {
1102 MemberSpecializationInfo *MSInfo
1103 = Function->getMemberSpecializationInfo();
1104 assert(MSInfo && "No member specialization information?");
1105 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1107 MSInfo->getTemplateSpecializationKind(),
1108 MSInfo->getPointOfInstantiation(),
1113 if (Function->getBody())
1116 if (TSK == TSK_ExplicitInstantiationDefinition) {
1117 // C++0x [temp.explicit]p8:
1118 // An explicit instantiation definition that names a class template
1119 // specialization explicitly instantiates the class template
1120 // specialization and is only an explicit instantiation definition
1121 // of members whose definition is visible at the point of
1123 if (!Pattern->getBody())
1126 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1128 InstantiateFunctionDefinition(PointOfInstantiation, Function);
1130 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1133 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1134 if (Var->isStaticDataMember()) {
1135 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
1136 assert(MSInfo && "No member specialization information?");
1137 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1139 MSInfo->getTemplateSpecializationKind(),
1140 MSInfo->getPointOfInstantiation(),
1145 if (TSK == TSK_ExplicitInstantiationDefinition) {
1146 // C++0x [temp.explicit]p8:
1147 // An explicit instantiation definition that names a class template
1148 // specialization explicitly instantiates the class template
1149 // specialization and is only an explicit instantiation definition
1150 // of members whose definition is visible at the point of
1152 if (!Var->getInstantiatedFromStaticDataMember()
1153 ->getOutOfLineDefinition())
1156 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1157 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
1159 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1162 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1163 if (Record->isInjectedClassName())
1166 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
1167 assert(MSInfo && "No member specialization information?");
1168 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1170 MSInfo->getTemplateSpecializationKind(),
1171 MSInfo->getPointOfInstantiation(),
1176 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
1177 assert(Pattern && "Missing instantiated-from-template information");
1179 if (!Record->getDefinition(Context)) {
1180 if (!Pattern->getDefinition(Context)) {
1181 // C++0x [temp.explicit]p8:
1182 // An explicit instantiation definition that names a class template
1183 // specialization explicitly instantiates the class template
1184 // specialization and is only an explicit instantiation definition
1185 // of members whose definition is visible at the point of
1187 if (TSK == TSK_ExplicitInstantiationDeclaration) {
1188 MSInfo->setTemplateSpecializationKind(TSK);
1189 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1195 InstantiateClass(PointOfInstantiation, Record, Pattern,
1200 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
1202 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
1208 /// \brief Instantiate the definitions of all of the members of the
1209 /// given class template specialization, which was named as part of an
1210 /// explicit instantiation.
1212 Sema::InstantiateClassTemplateSpecializationMembers(
1213 SourceLocation PointOfInstantiation,
1214 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1215 TemplateSpecializationKind TSK) {
1216 // C++0x [temp.explicit]p7:
1217 // An explicit instantiation that names a class template
1218 // specialization is an explicit instantion of the same kind
1219 // (declaration or definition) of each of its members (not
1220 // including members inherited from base classes) that has not
1221 // been previously explicitly specialized in the translation unit
1222 // containing the explicit instantiation, except as described
1224 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1225 getTemplateInstantiationArgs(ClassTemplateSpec),
1229 Sema::OwningStmtResult
1230 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
1234 TemplateInstantiator Instantiator(*this, TemplateArgs,
1237 return Instantiator.TransformStmt(S);
1240 Sema::OwningExprResult
1241 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
1245 TemplateInstantiator Instantiator(*this, TemplateArgs,
1248 return Instantiator.TransformExpr(E);
1251 /// \brief Do template substitution on a nested-name-specifier.
1252 NestedNameSpecifier *
1253 Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS,
1255 const MultiLevelTemplateArgumentList &TemplateArgs) {
1256 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
1258 return Instantiator.TransformNestedNameSpecifier(NNS, Range);
1262 Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc,
1263 const MultiLevelTemplateArgumentList &TemplateArgs) {
1264 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1266 return Instantiator.TransformTemplateName(Name);
1269 bool Sema::Subst(const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
1270 const MultiLevelTemplateArgumentList &TemplateArgs) {
1271 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
1274 return Instantiator.TransformTemplateArgument(Input, Output);