blob: 80dcfd4e6d254d10dd0ef9df1c41e991dcf95661 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000019#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021
22using namespace clang;
23
24namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000025 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000026 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000027 Sema &SemaRef;
28 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000029 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Anders Carlssond8fe2d52009-11-07 06:07:58 +000031 void InstantiateAttrs(Decl *Tmpl, Decl *New);
32
Douglas Gregor8dbc2692009-03-17 21:15:40 +000033 public:
34 typedef Sema::OwningExprResult OwningExprResult;
35
36 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000037 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000038 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000039
Mike Stump390b4cc2009-05-16 07:39:55 +000040 // FIXME: Once we get closer to completion, replace these manually-written
41 // declarations with automatically-generated ones from
42 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000043 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
44 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000045 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000046 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitFieldDecl(FieldDecl *D);
48 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
49 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000050 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000051 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000052 Decl *VisitFunctionDecl(FunctionDecl *D,
53 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000054 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000055 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
56 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000057 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000058 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000059 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000060 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000061 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000062 Decl *VisitClassTemplatePartialSpecializationDecl(
63 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000064 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000066 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000067 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000068 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000069 Decl *VisitUsingDecl(UsingDecl *D);
70 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000071 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
72 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000073
Douglas Gregor8dbc2692009-03-17 21:15:40 +000074 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000075 Decl *VisitDecl(Decl *D) {
76 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
77 Diagnostic::Error,
78 "cannot instantiate %0 yet");
79 SemaRef.Diag(D->getLocation(), DiagID)
80 << D->getDeclKindName();
81
Douglas Gregor8dbc2692009-03-17 21:15:40 +000082 return 0;
83 }
Douglas Gregor5545e162009-03-24 00:38:23 +000084
John McCallfd810b12009-08-14 02:03:10 +000085 const LangOptions &getLangOptions() {
86 return SemaRef.getLangOptions();
87 }
88
Douglas Gregor5545e162009-03-24 00:38:23 +000089 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000090 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000091 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000092 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000093 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000094
95 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000096 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000097
98 bool InstantiateClassTemplatePartialSpecialization(
99 ClassTemplateDecl *ClassTemplate,
100 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000101 };
102}
103
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000104// FIXME: Is this too simple?
105void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
106 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
107 TmplAttr = TmplAttr->getNext()) {
108
109 // FIXME: Is cloning correct for all attributes?
110 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
111
112 New->addAttr(NewAttr);
113 }
114}
115
Douglas Gregor4f722be2009-03-25 15:45:12 +0000116Decl *
117TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
118 assert(false && "Translation units cannot be instantiated");
119 return D;
120}
121
122Decl *
123TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
124 assert(false && "Namespaces cannot be instantiated");
125 return D;
126}
127
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000128Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
129 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000130 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000131 if (DI->getType()->isDependentType()) {
132 DI = SemaRef.SubstType(DI, TemplateArgs,
133 D->getLocation(), D->getDeclName());
134 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000135 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000136 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000137 }
138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000140 // Create the new typedef
141 TypedefDecl *Typedef
142 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000143 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000144 if (Invalid)
145 Typedef->setInvalidDecl();
146
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000147 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000149 return Typedef;
150}
151
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000152Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000153 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000154 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000155 TemplateArgs,
156 D->getTypeSpecStartLoc(),
157 D->getDeclName());
158 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000159 return 0;
160
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000161 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000162 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
163 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000164 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000165 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000166 Var->setThreadSpecified(D->isThreadSpecified());
167 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
168 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000169
170 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000171 // out-of-line, the instantiation will have the same lexical
172 // context (which will be a namespace scope) as the template.
173 if (D->isOutOfLine())
174 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Mike Stump390b4cc2009-05-16 07:39:55 +0000176 // FIXME: In theory, we could have a previous declaration for variables that
177 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000178 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000179 // FIXME: having to fake up a LookupResult is dumb.
180 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
181 Sema::LookupOrdinaryName);
182 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Douglas Gregor7caa6822009-07-24 20:34:43 +0000184 if (D->isOutOfLine()) {
185 D->getLexicalDeclContext()->addDecl(Var);
186 Owner->makeDeclVisibleInContext(Var);
187 } else {
188 Owner->addDecl(Var);
189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000191 // Link instantiations of static data members back to the template from
192 // which they were instantiated.
193 if (Var->isStaticDataMember())
194 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000195 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000196
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000197 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000198 if (Var->isStaticDataMember() && !D->isOutOfLine())
199 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
200 else
201 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
202
Mike Stump1eb44332009-09-09 15:08:12 +0000203 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000204 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000205 if (Init.isInvalid())
206 Var->setInvalidDecl();
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000207 else if (!D->getType()->isDependentType() &&
208 !D->getInit()->isTypeDependent() &&
Douglas Gregore48319a2009-11-09 17:16:50 +0000209 !D->getInit()->isValueDependent()) {
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000210 // If neither the declaration's type nor its initializer are dependent,
211 // we don't want to redo all the checking, especially since the
212 // initializer might have been wrapped by a CXXConstructExpr since we did
213 // it the first time.
Anders Carlssona244dc32009-11-24 16:52:50 +0000214 Var->setType(D->getType());
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000215 Var->setInit(SemaRef.Context, Init.takeAs<Expr>());
216 }
Douglas Gregor83ddad32009-08-26 21:14:46 +0000217 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000218 // FIXME: We're faking all of the comma locations, which is suboptimal.
Douglas Gregor83ddad32009-08-26 21:14:46 +0000219 // Do we even need these comma locations?
220 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
221 if (PLE->getNumExprs() > 0) {
222 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
223 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
224 Expr *E = PLE->getExpr(I)->Retain();
225 FakeCommaLocs.push_back(
226 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
227 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000228 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000229 }
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Douglas Gregor83ddad32009-08-26 21:14:46 +0000231 // Add the direct initializer to the declaration.
232 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Mike Stump1eb44332009-09-09 15:08:12 +0000233 PLE->getLParenLoc(),
Douglas Gregor83ddad32009-08-26 21:14:46 +0000234 Sema::MultiExprArg(SemaRef,
235 (void**)PLE->getExprs(),
236 PLE->getNumExprs()),
237 FakeCommaLocs.data(),
238 PLE->getRParenLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Douglas Gregor83ddad32009-08-26 21:14:46 +0000240 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
241 // we've explicitly retained all of its subexpressions already.
242 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000243 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000244 D->hasCXXDirectInitializer());
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000245 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000246 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
247 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000248
249 return Var;
250}
251
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000252Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
253 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000254 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000255 if (DI->getType()->isDependentType()) {
256 DI = SemaRef.SubstType(DI, TemplateArgs,
257 D->getLocation(), D->getDeclName());
258 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000259 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000260 Invalid = true;
261 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000262 // C++ [temp.arg.type]p3:
263 // If a declaration acquires a function type through a type
264 // dependent on a template-parameter and this causes a
265 // declaration that does not use the syntactic form of a
266 // function declarator to have function type, the program is
267 // ill-formed.
268 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000269 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000270 Invalid = true;
271 }
272 }
273
274 Expr *BitWidth = D->getBitWidth();
275 if (Invalid)
276 BitWidth = 0;
277 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000278 // The bit-width expression is not potentially evaluated.
279 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000281 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000282 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000283 if (InstantiatedBitWidth.isInvalid()) {
284 Invalid = true;
285 BitWidth = 0;
286 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000287 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000288 }
289
John McCall07fb6be2009-10-22 23:33:21 +0000290 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
291 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000292 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000293 D->getLocation(),
294 D->isMutable(),
295 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000296 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000297 D->getAccess(),
298 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000299 if (!Field) {
300 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000301 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000302 }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000304 InstantiateAttrs(D, Field);
305
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000306 if (Invalid)
307 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000309 if (!Field->getDeclName()) {
310 // Keep track of where this decl came from.
311 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000314 Field->setImplicit(D->isImplicit());
315 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000316
317 return Field;
318}
319
John McCall02cace72009-08-28 07:59:38 +0000320Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
321 FriendDecl::FriendUnion FU;
322
323 // Handle friend type expressions by simply substituting template
324 // parameters into the pattern type.
325 if (Type *Ty = D->getFriendType()) {
326 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
327 D->getLocation(), DeclarationName());
328 if (T.isNull()) return 0;
329
330 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
331 FU = T.getTypePtr();
332
333 // Handle everything else by appropriate substitution.
334 } else {
335 NamedDecl *ND = D->getFriendDecl();
336 assert(ND && "friend decl must be a decl or a type!");
337
Douglas Gregora735b202009-10-13 14:39:41 +0000338 // FIXME: We have a problem here, because the nested call to Visit(ND)
339 // will inject the thing that the friend references into the current
340 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000341 Decl *NewND = Visit(ND);
342 if (!NewND) return 0;
343
344 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000345 }
Mike Stump1eb44332009-09-09 15:08:12 +0000346
John McCall02cace72009-08-28 07:59:38 +0000347 FriendDecl *FD =
348 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
349 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000350 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000351 Owner->addDecl(FD);
352 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000353}
354
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000355Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
356 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Douglas Gregorac7610d2009-06-22 20:57:11 +0000358 // The expression in a static assertion is not potentially evaluated.
359 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000361 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000362 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000363 if (InstantiatedAssertExpr.isInvalid())
364 return 0;
365
Douglas Gregor43d9d922009-08-08 01:41:12 +0000366 OwningExprResult Message(SemaRef, D->getMessage());
367 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000368 Decl *StaticAssert
369 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000370 move(InstantiatedAssertExpr),
371 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000372 return StaticAssert;
373}
374
375Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000376 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000377 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000378 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000379 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000380 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000381 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000382 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383 Enum->startDefinition();
384
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000385 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000386
387 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000388 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
389 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000390 EC != ECEnd; ++EC) {
391 // The specified value for the enumerator.
392 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000393 if (Expr *UninstValue = EC->getInitExpr()) {
394 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000395 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000396 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
John McCallce3ff2b2009-08-25 22:02:44 +0000398 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000399 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000400
401 // Drop the initial value and continue.
402 bool isInvalid = false;
403 if (Value.isInvalid()) {
404 Value = SemaRef.Owned((Expr *)0);
405 isInvalid = true;
406 }
407
Mike Stump1eb44332009-09-09 15:08:12 +0000408 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000409 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
410 EC->getLocation(), EC->getIdentifier(),
411 move(Value));
412
413 if (isInvalid) {
414 if (EnumConst)
415 EnumConst->setInvalidDecl();
416 Enum->setInvalidDecl();
417 }
418
419 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000420 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000421 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000422 LastEnumConst = EnumConst;
423 }
424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000426 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000427 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000428 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
429 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000430 &Enumerators[0], Enumerators.size(),
431 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000432
433 return Enum;
434}
435
Douglas Gregor6477b692009-03-25 15:04:13 +0000436Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
437 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
438 return 0;
439}
440
Douglas Gregored9c0f92009-10-29 00:04:11 +0000441namespace {
442 class SortDeclByLocation {
443 SourceManager &SourceMgr;
444
445 public:
446 explicit SortDeclByLocation(SourceManager &SourceMgr)
447 : SourceMgr(SourceMgr) { }
448
449 bool operator()(const Decl *X, const Decl *Y) const {
450 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
451 Y->getLocation());
452 }
453 };
454}
455
John McCalle29ba202009-08-20 01:44:21 +0000456Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000457 // Create a local instantiation scope for this class template, which
458 // will contain the instantiations of the template parameters.
459 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000460 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000461 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000462 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000463 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000464
465 CXXRecordDecl *Pattern = D->getTemplatedDecl();
466 CXXRecordDecl *RecordInst
467 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
468 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000469 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
470 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000471
472 ClassTemplateDecl *Inst
473 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
474 D->getIdentifier(), InstParams, RecordInst, 0);
475 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000476 if (D->getFriendObjectKind())
477 Inst->setObjectOfFriendDecl(true);
478 else
479 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000480 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000481
482 // Trigger creation of the type for the instantiation.
483 SemaRef.Context.getTypeDeclType(RecordInst);
484
Douglas Gregor259571e2009-10-30 22:42:42 +0000485 // Finish handling of friends.
486 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000487 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000488 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000489
John McCalle29ba202009-08-20 01:44:21 +0000490 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000491
492 // First, we sort the partial specializations by location, so
493 // that we instantiate them in the order they were declared.
494 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
495 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
496 P = D->getPartialSpecializations().begin(),
497 PEnd = D->getPartialSpecializations().end();
498 P != PEnd; ++P)
499 PartialSpecs.push_back(&*P);
500 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
501 SortDeclByLocation(SemaRef.SourceMgr));
502
503 // Instantiate all of the partial specializations of this member class
504 // template.
505 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
506 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
507
John McCalle29ba202009-08-20 01:44:21 +0000508 return Inst;
509}
510
Douglas Gregord60e1052009-08-27 16:57:43 +0000511Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000512TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
513 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000514 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
515
516 // Lookup the already-instantiated declaration in the instantiation
517 // of the class template and return that.
518 DeclContext::lookup_result Found
519 = Owner->lookup(ClassTemplate->getDeclName());
520 if (Found.first == Found.second)
521 return 0;
522
523 ClassTemplateDecl *InstClassTemplate
524 = dyn_cast<ClassTemplateDecl>(*Found.first);
525 if (!InstClassTemplate)
526 return 0;
527
528 Decl *DCanon = D->getCanonicalDecl();
529 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
530 P = InstClassTemplate->getPartialSpecializations().begin(),
531 PEnd = InstClassTemplate->getPartialSpecializations().end();
532 P != PEnd; ++P) {
533 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
534 return &*P;
535 }
536
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000537 return 0;
538}
539
540Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000541TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000542 // Create a local instantiation scope for this function template, which
543 // will contain the instantiations of the template parameters and then get
544 // merged with the local instantiation scope for the function template
545 // itself.
546 Sema::LocalInstantiationScope Scope(SemaRef);
547
Douglas Gregord60e1052009-08-27 16:57:43 +0000548 TemplateParameterList *TempParams = D->getTemplateParameters();
549 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000550 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000551 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000552
Douglas Gregora735b202009-10-13 14:39:41 +0000553 FunctionDecl *Instantiated = 0;
554 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
555 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
556 InstParams));
557 else
558 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
559 D->getTemplatedDecl(),
560 InstParams));
561
562 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000563 return 0;
564
Mike Stump1eb44332009-09-09 15:08:12 +0000565 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000566 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000567 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000568 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000569 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000570 assert(InstTemplate &&
571 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
572 if (!InstTemplate->getInstantiatedFromMemberTemplate())
573 InstTemplate->setInstantiatedFromMemberTemplate(D);
574
575 // Add non-friends into the owner.
576 if (!InstTemplate->getFriendObjectKind())
577 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000578 return InstTemplate;
579}
580
Douglas Gregord475b8d2009-03-25 21:17:03 +0000581Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
582 CXXRecordDecl *PrevDecl = 0;
583 if (D->isInjectedClassName())
584 PrevDecl = cast<CXXRecordDecl>(Owner);
585
586 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000587 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000588 D->getLocation(), D->getIdentifier(),
589 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000590 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000591 // FIXME: Check against AS_none is an ugly hack to work around the issue that
592 // the tag decls introduced by friend class declarations don't have an access
593 // specifier. Remove once this area of the code gets sorted out.
594 if (D->getAccess() != AS_none)
595 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000596 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000597 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000598
John McCall02cace72009-08-28 07:59:38 +0000599 // If the original function was part of a friend declaration,
600 // inherit its namespace state.
601 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
602 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
603
Anders Carlssond8b285f2009-09-01 04:26:58 +0000604 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
605
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000606 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000607 return Record;
608}
609
John McCall02cace72009-08-28 07:59:38 +0000610/// Normal class members are of more specific types and therefore
611/// don't make it here. This function serves two purposes:
612/// 1) instantiating function templates
613/// 2) substituting friend declarations
614/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000615 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
616 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000617 // Check whether there is already a function template specialization for
618 // this declaration.
619 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
620 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000621 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000622 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000623 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000624 TemplateArgs.getInnermost().getFlatArgumentList(),
625 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000626 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000627
628 FunctionTemplateSpecializationInfo *Info
629 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000630 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Douglas Gregor127102b2009-06-29 20:59:39 +0000632 // If we already have a function template specialization, return it.
633 if (Info)
634 return Info->Function;
635 }
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregor550d9b22009-10-31 17:21:17 +0000637 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Douglas Gregore53060f2009-06-25 22:08:12 +0000639 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000640 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000641 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000642 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000643
Douglas Gregore53060f2009-06-25 22:08:12 +0000644 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000645 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
646 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000647 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000648 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000649 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000650 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000651 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000652 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Douglas Gregore53060f2009-06-25 22:08:12 +0000654 // Attach the parameters
655 for (unsigned P = 0; P < Params.size(); ++P)
656 Params[P]->setOwningFunction(Function);
657 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000658
Douglas Gregora735b202009-10-13 14:39:41 +0000659 if (TemplateParams) {
660 // Our resulting instantiation is actually a function template, since we
661 // are substituting only the outer template parameters. For example, given
662 //
663 // template<typename T>
664 // struct X {
665 // template<typename U> friend void f(T, U);
666 // };
667 //
668 // X<int> x;
669 //
670 // We are instantiating the friend function template "f" within X<int>,
671 // which means substituting int for T, but leaving "f" as a friend function
672 // template.
673 // Build the function template itself.
674 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
675 Function->getLocation(),
676 Function->getDeclName(),
677 TemplateParams, Function);
678 Function->setDescribedFunctionTemplate(FunctionTemplate);
679 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000680 } else if (FunctionTemplate) {
681 // Record this function template specialization.
682 Function->setFunctionTemplateSpecialization(SemaRef.Context,
683 FunctionTemplate,
684 &TemplateArgs.getInnermost(),
685 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000686 }
Douglas Gregora735b202009-10-13 14:39:41 +0000687
Douglas Gregore53060f2009-06-25 22:08:12 +0000688 if (InitFunctionInstantiation(Function, D))
689 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Douglas Gregore53060f2009-06-25 22:08:12 +0000691 bool Redeclaration = false;
692 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000693
John McCall68263142009-11-18 22:49:29 +0000694 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
695 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
696
Douglas Gregora735b202009-10-13 14:39:41 +0000697 if (TemplateParams || !FunctionTemplate) {
698 // Look only into the namespace where the friend would be declared to
699 // find a previous declaration. This is the innermost enclosing namespace,
700 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000701 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000702
Douglas Gregora735b202009-10-13 14:39:41 +0000703 // In C++, the previous declaration we find might be a tag type
704 // (class or enum). In this case, the new declaration will hide the
705 // tag type. Note that this does does not apply if we're declaring a
706 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000707 if (Previous.isSingleTagDecl())
708 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000709 }
710
John McCall68263142009-11-18 22:49:29 +0000711 SemaRef.CheckFunctionDeclaration(Function, Previous, false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000712 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000713
Douglas Gregora735b202009-10-13 14:39:41 +0000714 // If the original function was part of a friend declaration,
715 // inherit its namespace state and add it to the owner.
716 NamedDecl *FromFriendD
717 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
718 if (FromFriendD->getFriendObjectKind()) {
719 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000720 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000721 if (TemplateParams) {
722 ToFriendD = cast<NamedDecl>(FunctionTemplate);
723 PrevDecl = FunctionTemplate->getPreviousDeclaration();
724 } else {
725 ToFriendD = Function;
726 PrevDecl = Function->getPreviousDeclaration();
727 }
728 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
729 if (!Owner->isDependentContext() && !PrevDecl)
730 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
731
732 if (!TemplateParams)
733 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
734 }
735
Douglas Gregore53060f2009-06-25 22:08:12 +0000736 return Function;
737}
738
Douglas Gregord60e1052009-08-27 16:57:43 +0000739Decl *
740TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
741 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000742 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
743 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000744 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000745 // We are creating a function template specialization from a function
746 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000747 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000748 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000749 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000750 TemplateArgs.getInnermost().getFlatArgumentList(),
751 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000752 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000753
754 FunctionTemplateSpecializationInfo *Info
755 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000756 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Douglas Gregor6b906862009-08-21 00:16:32 +0000758 // If we already have a function template specialization, return it.
759 if (Info)
760 return Info->Function;
761 }
762
Douglas Gregor550d9b22009-10-31 17:21:17 +0000763 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000764
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000765 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000766 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000767 if (T.isNull())
768 return 0;
769
770 // Build the instantiated method declaration.
771 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000772 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Douglas Gregordec06662009-08-21 18:42:58 +0000774 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000775 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000776 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
777 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
778 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000779 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
780 Constructor->getLocation(),
781 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000782 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000783 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000784 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000785 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
786 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
787 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
788 SemaRef.Context.getCanonicalType(ClassTy));
789 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
790 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000791 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000792 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000793 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000794 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000795 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000796 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
797 ConvTy);
798 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
799 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000800 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000801 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000802 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000803 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000804 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000805 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000806 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000807 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000808
Douglas Gregord60e1052009-08-27 16:57:43 +0000809 if (TemplateParams) {
810 // Our resulting instantiation is actually a function template, since we
811 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000812 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000813 // template<typename T>
814 // struct X {
815 // template<typename U> void f(T, U);
816 // };
817 //
818 // X<int> x;
819 //
820 // We are instantiating the member template "f" within X<int>, which means
821 // substituting int for T, but leaving "f" as a member function template.
822 // Build the function template itself.
823 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
824 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000825 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000826 TemplateParams, Method);
827 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000828 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000829 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000830 } else if (FunctionTemplate) {
831 // Record this function template specialization.
832 Method->setFunctionTemplateSpecialization(SemaRef.Context,
833 FunctionTemplate,
834 &TemplateArgs.getInnermost(),
835 InsertPos);
836 } else {
837 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000838 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000839 }
840
Mike Stump1eb44332009-09-09 15:08:12 +0000841 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000842 // out-of-line, the instantiation will have the same lexical
843 // context (which will be a namespace scope) as the template.
844 if (D->isOutOfLine())
845 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Douglas Gregor5545e162009-03-24 00:38:23 +0000847 // Attach the parameters
848 for (unsigned P = 0; P < Params.size(); ++P)
849 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000850 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000851
852 if (InitMethodInstantiation(Method, D))
853 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000854
John McCall68263142009-11-18 22:49:29 +0000855 LookupResult Previous(SemaRef, Name, SourceLocation(),
856 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Douglas Gregord60e1052009-08-27 16:57:43 +0000858 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000859 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Douglas Gregordec06662009-08-21 18:42:58 +0000861 // In C++, the previous declaration we find might be a tag type
862 // (class or enum). In this case, the new declaration will hide the
863 // tag type. Note that this does does not apply if we're declaring a
864 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000865 if (Previous.isSingleTagDecl())
866 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000867 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000868
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000869 bool Redeclaration = false;
870 bool OverloadableAttrRequired = false;
John McCall68263142009-11-18 22:49:29 +0000871 SemaRef.CheckFunctionDeclaration(Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000872 /*FIXME:*/OverloadableAttrRequired);
873
Douglas Gregor4ba31362009-12-01 17:24:26 +0000874 if (D->isPure())
875 SemaRef.CheckPureMethod(Method, SourceRange());
876
John McCall68263142009-11-18 22:49:29 +0000877 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000878 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000879 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000881 return Method;
882}
883
Douglas Gregor615c5d42009-03-24 16:43:20 +0000884Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000885 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000886}
887
Douglas Gregor03b2b072009-03-24 00:15:49 +0000888Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000889 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000890}
891
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000892Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000893 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000894}
895
Douglas Gregor6477b692009-03-25 15:04:13 +0000896ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000897 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000898 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000899 if (DI) {
900 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
901 D->getDeclName());
902 if (DI) T = DI->getType();
903 } else {
904 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
905 D->getDeclName());
906 DI = 0;
907 }
908
909 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000910 return 0;
911
John McCall58e46772009-10-23 21:48:59 +0000912 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000913
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000914 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000915 ParmVarDecl *Param
916 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
917 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000918
Anders Carlsson9351c172009-08-25 03:18:48 +0000919 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000920 if (D->hasUninstantiatedDefaultArg())
921 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000922 else if (Expr *Arg = D->getDefaultArg())
923 Param->setUninstantiatedDefaultArg(Arg);
924
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000925 // Note: we don't try to instantiate function parameters until after
926 // we've instantiated the function's type. Therefore, we don't have
927 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000928 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000929 return Param;
930}
931
John McCalle29ba202009-08-20 01:44:21 +0000932Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
933 TemplateTypeParmDecl *D) {
934 // TODO: don't always clone when decls are refcounted.
935 const Type* T = D->getTypeForDecl();
936 assert(T->isTemplateTypeParmType());
937 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000938
John McCalle29ba202009-08-20 01:44:21 +0000939 TemplateTypeParmDecl *Inst =
940 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +0000941 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +0000942 TTPT->getName(),
943 D->wasDeclaredWithTypename(),
944 D->isParameterPack());
945
Douglas Gregor0f8716b2009-11-09 19:17:50 +0000946 if (D->hasDefaultArgument())
947 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +0000948
Douglas Gregor550d9b22009-10-31 17:21:17 +0000949 // Introduce this template parameter's instantiation into the instantiation
950 // scope.
951 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
952
John McCalle29ba202009-08-20 01:44:21 +0000953 return Inst;
954}
955
Douglas Gregor33642df2009-10-23 23:25:44 +0000956Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
957 NonTypeTemplateParmDecl *D) {
958 // Substitute into the type of the non-type template parameter.
959 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000960 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +0000961 if (DI) {
962 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
963 D->getDeclName());
964 if (DI) T = DI->getType();
965 } else {
966 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
967 D->getDeclName());
968 DI = 0;
969 }
970 if (T.isNull())
971 return 0;
972
973 // Check that this type is acceptable for a non-type template parameter.
974 bool Invalid = false;
975 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
976 if (T.isNull()) {
977 T = SemaRef.Context.IntTy;
978 Invalid = true;
979 }
980
981 NonTypeTemplateParmDecl *Param
982 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
983 D->getDepth() - 1, D->getPosition(),
984 D->getIdentifier(), T, DI);
985 if (Invalid)
986 Param->setInvalidDecl();
987
988 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +0000989
990 // Introduce this template parameter's instantiation into the instantiation
991 // scope.
992 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +0000993 return Param;
994}
995
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000996Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +0000997TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
998 TemplateTemplateParmDecl *D) {
999 // Instantiate the template parameter list of the template template parameter.
1000 TemplateParameterList *TempParams = D->getTemplateParameters();
1001 TemplateParameterList *InstParams;
1002 {
1003 // Perform the actual substitution of template parameters within a new,
1004 // local instantiation scope.
1005 Sema::LocalInstantiationScope Scope(SemaRef);
1006 InstParams = SubstTemplateParams(TempParams);
1007 if (!InstParams)
1008 return NULL;
1009 }
1010
1011 // Build the template template parameter.
1012 TemplateTemplateParmDecl *Param
1013 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1014 D->getDepth() - 1, D->getPosition(),
1015 D->getIdentifier(), InstParams);
1016 Param->setDefaultArgument(D->getDefaultArgument());
1017
1018 // Introduce this template parameter's instantiation into the instantiation
1019 // scope.
1020 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1021
1022 return Param;
1023}
1024
Douglas Gregor48c32a72009-11-17 06:07:40 +00001025Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1026 // Using directives are never dependent, so they require no explicit
1027
1028 UsingDirectiveDecl *Inst
1029 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1030 D->getNamespaceKeyLocation(),
1031 D->getQualifierRange(), D->getQualifier(),
1032 D->getIdentLocation(),
1033 D->getNominatedNamespace(),
1034 D->getCommonAncestor());
1035 Owner->addDecl(Inst);
1036 return Inst;
1037}
1038
John McCalled976492009-12-04 22:46:56 +00001039Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1040 // The nested name specifier is non-dependent, so no transformation
1041 // is required.
1042
1043 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1044 D->getLocation(),
1045 D->getNestedNameRange(),
1046 D->getUsingLocation(),
1047 D->getTargetNestedNameDecl(),
1048 D->getDeclName(),
1049 D->isTypeName());
1050
1051 CXXScopeSpec SS;
1052 SS.setScopeRep(D->getTargetNestedNameDecl());
1053 SS.setRange(D->getNestedNameRange());
1054 if (SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1055 D->getLocation()))
1056 NewUD->setInvalidDecl();
1057 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1058 NewUD->setAccess(D->getAccess());
1059 Owner->addDecl(NewUD);
1060
1061 // We'll transform the UsingShadowDecls as we reach them.
1062
1063 return NewUD;
1064}
1065
1066Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1067 UsingDecl *InstUsing =
1068 cast<UsingDecl>(SemaRef.FindInstantiatedDecl(D->getUsingDecl(),
1069 TemplateArgs));
1070 NamedDecl *InstTarget =
1071 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(D->getTargetDecl(),
1072 TemplateArgs));
1073
John McCall604e7f12009-12-08 07:46:18 +00001074 UsingShadowDecl *InstD = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0,
1075 D->getAccess(),
1076 InstUsing,
1077 InstTarget);
John McCalled976492009-12-04 22:46:56 +00001078
1079 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstD, D);
John McCalled976492009-12-04 22:46:56 +00001080
1081 return InstD;
1082}
1083
John McCall7ba107a2009-11-18 02:36:19 +00001084Decl * TemplateDeclInstantiator
1085 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001086 NestedNameSpecifier *NNS =
1087 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1088 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001089 TemplateArgs);
1090 if (!NNS)
1091 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001093 CXXScopeSpec SS;
1094 SS.setRange(D->getTargetNestedNameRange());
1095 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001096
1097 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001098 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001099 D->getUsingLoc(), SS, D->getLocation(),
1100 D->getDeclName(), 0,
1101 /*instantiation*/ true,
1102 /*typename*/ true, D->getTypenameLoc());
1103 if (UD)
John McCalled976492009-12-04 22:46:56 +00001104 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1105
John McCall7ba107a2009-11-18 02:36:19 +00001106 return UD;
1107}
1108
1109Decl * TemplateDeclInstantiator
1110 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1111 NestedNameSpecifier *NNS =
1112 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1113 D->getTargetNestedNameRange(),
1114 TemplateArgs);
1115 if (!NNS)
1116 return 0;
1117
1118 CXXScopeSpec SS;
1119 SS.setRange(D->getTargetNestedNameRange());
1120 SS.setScopeRep(NNS);
1121
1122 NamedDecl *UD =
1123 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1124 D->getUsingLoc(), SS, D->getLocation(),
1125 D->getDeclName(), 0,
1126 /*instantiation*/ true,
1127 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001128 if (UD)
John McCalled976492009-12-04 22:46:56 +00001129 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1130
Anders Carlsson0d8df782009-08-29 19:37:28 +00001131 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001132}
1133
John McCallce3ff2b2009-08-25 22:02:44 +00001134Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001135 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001136 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001137 return Instantiator.Visit(D);
1138}
1139
John McCalle29ba202009-08-20 01:44:21 +00001140/// \brief Instantiates a nested template parameter list in the current
1141/// instantiation context.
1142///
1143/// \param L The parameter list to instantiate
1144///
1145/// \returns NULL if there was an error
1146TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001147TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001148 // Get errors for all the parameters before bailing out.
1149 bool Invalid = false;
1150
1151 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001152 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001153 ParamVector Params;
1154 Params.reserve(N);
1155 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1156 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001157 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001158 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001159 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001160 }
1161
1162 // Clean up if we had an error.
1163 if (Invalid) {
1164 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1165 PI != PE; ++PI)
1166 if (*PI)
1167 (*PI)->Destroy(SemaRef.Context);
1168 return NULL;
1169 }
1170
1171 TemplateParameterList *InstL
1172 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1173 L->getLAngleLoc(), &Params.front(), N,
1174 L->getRAngleLoc());
1175 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001176}
John McCalle29ba202009-08-20 01:44:21 +00001177
Douglas Gregored9c0f92009-10-29 00:04:11 +00001178/// \brief Instantiate the declaration of a class template partial
1179/// specialization.
1180///
1181/// \param ClassTemplate the (instantiated) class template that is partially
1182// specialized by the instantiation of \p PartialSpec.
1183///
1184/// \param PartialSpec the (uninstantiated) class template partial
1185/// specialization that we are instantiating.
1186///
1187/// \returns true if there was an error, false otherwise.
1188bool
1189TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1190 ClassTemplateDecl *ClassTemplate,
1191 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001192 // Create a local instantiation scope for this class template partial
1193 // specialization, which will contain the instantiations of the template
1194 // parameters.
1195 Sema::LocalInstantiationScope Scope(SemaRef);
1196
Douglas Gregored9c0f92009-10-29 00:04:11 +00001197 // Substitute into the template parameters of the class template partial
1198 // specialization.
1199 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1200 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1201 if (!InstParams)
1202 return true;
1203
1204 // Substitute into the template arguments of the class template partial
1205 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001206 const TemplateArgumentLoc *PartialSpecTemplateArgs
1207 = PartialSpec->getTemplateArgsAsWritten();
1208 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1209
John McCalld5532b62009-11-23 01:53:49 +00001210 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001211 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001212 TemplateArgumentLoc Loc;
1213 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001214 return true;
John McCalld5532b62009-11-23 01:53:49 +00001215 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001216 }
1217
1218
1219 // Check that the template argument list is well-formed for this
1220 // class template.
1221 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1222 InstTemplateArgs.size());
1223 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1224 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001225 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001226 false,
1227 Converted))
1228 return true;
1229
1230 // Figure out where to insert this class template partial specialization
1231 // in the member template's set of class template partial specializations.
1232 llvm::FoldingSetNodeID ID;
1233 ClassTemplatePartialSpecializationDecl::Profile(ID,
1234 Converted.getFlatArguments(),
1235 Converted.flatSize(),
1236 SemaRef.Context);
1237 void *InsertPos = 0;
1238 ClassTemplateSpecializationDecl *PrevDecl
1239 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1240 InsertPos);
1241
1242 // Build the canonical type that describes the converted template
1243 // arguments of the class template partial specialization.
1244 QualType CanonType
1245 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1246 Converted.getFlatArguments(),
1247 Converted.flatSize());
1248
1249 // Build the fully-sugared type for this class template
1250 // specialization as the user wrote in the specialization
1251 // itself. This means that we'll pretty-print the type retrieved
1252 // from the specialization's declaration the way that the user
1253 // actually wrote the specialization, rather than formatting the
1254 // name based on the "canonical" representation used to store the
1255 // template arguments in the specialization.
1256 QualType WrittenTy
1257 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001258 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001259 CanonType);
1260
1261 if (PrevDecl) {
1262 // We've already seen a partial specialization with the same template
1263 // parameters and template arguments. This can happen, for example, when
1264 // substituting the outer template arguments ends up causing two
1265 // class template partial specializations of a member class template
1266 // to have identical forms, e.g.,
1267 //
1268 // template<typename T, typename U>
1269 // struct Outer {
1270 // template<typename X, typename Y> struct Inner;
1271 // template<typename Y> struct Inner<T, Y>;
1272 // template<typename Y> struct Inner<U, Y>;
1273 // };
1274 //
1275 // Outer<int, int> outer; // error: the partial specializations of Inner
1276 // // have the same signature.
1277 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1278 << WrittenTy;
1279 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1280 << SemaRef.Context.getTypeDeclType(PrevDecl);
1281 return true;
1282 }
1283
1284
1285 // Create the class template partial specialization declaration.
1286 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1287 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1288 PartialSpec->getLocation(),
1289 InstParams,
1290 ClassTemplate,
1291 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001292 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001293 0);
1294 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1295 InstPartialSpec->setTypeAsWritten(WrittenTy);
1296
1297 // Add this partial specialization to the set of class template partial
1298 // specializations.
1299 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1300 InsertPos);
1301 return false;
1302}
1303
John McCallce3ff2b2009-08-25 22:02:44 +00001304/// \brief Does substitution on the type of the given function, including
1305/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001306///
John McCallce3ff2b2009-08-25 22:02:44 +00001307/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001308///
1309/// \param Params the instantiated parameter declarations
1310
John McCallce3ff2b2009-08-25 22:02:44 +00001311/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001312/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001313QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001314TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001315 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1316 bool InvalidDecl = false;
1317
John McCallce3ff2b2009-08-25 22:02:44 +00001318 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001319 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001320 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001321 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001322 PEnd = D->param_end();
1323 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001324 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001325 if (PInst->getType()->isVoidType()) {
1326 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1327 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001328 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001329 PInst->getType(),
1330 diag::err_abstract_type_in_decl,
1331 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001332 PInst->setInvalidDecl();
1333
1334 Params.push_back(PInst);
1335 ParamTys.push_back(PInst->getType());
1336
1337 if (PInst->isInvalidDecl())
1338 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001339 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001340 InvalidDecl = true;
1341 }
1342
1343 // FIXME: Deallocate dead declarations.
1344 if (InvalidDecl)
1345 return QualType();
1346
John McCall183700f2009-09-21 23:43:11 +00001347 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001348 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001349 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001350 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1351 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001352 if (ResultType.isNull())
1353 return QualType();
1354
Jay Foadbeaaccd2009-05-21 09:52:38 +00001355 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001356 Proto->isVariadic(), Proto->getTypeQuals(),
1357 D->getLocation(), D->getDeclName());
1358}
1359
Mike Stump1eb44332009-09-09 15:08:12 +00001360/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001361/// declaration (New) from the corresponding fields of its template (Tmpl).
1362///
1363/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001364bool
1365TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001366 FunctionDecl *Tmpl) {
1367 if (Tmpl->isDeleted())
1368 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Douglas Gregorcca9e962009-07-01 22:01:06 +00001370 // If we are performing substituting explicitly-specified template arguments
1371 // or deduced template arguments into a function template and we reach this
1372 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001373 // to keeping the new function template specialization. We therefore
1374 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001375 // into a template instantiation for this specific function template
1376 // specialization, which is not a SFINAE context, so that we diagnose any
1377 // further errors in the declaration itself.
1378 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1379 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1380 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1381 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001382 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001383 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001384 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001385 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001386 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001387 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1388 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001389 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001390 }
1391 }
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001393 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1394 assert(Proto && "Function template without prototype?");
1395
1396 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1397 Proto->getNoReturnAttr()) {
1398 // The function has an exception specification or a "noreturn"
1399 // attribute. Substitute into each of the exception types.
1400 llvm::SmallVector<QualType, 4> Exceptions;
1401 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1402 // FIXME: Poor location information!
1403 QualType T
1404 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1405 New->getLocation(), New->getDeclName());
1406 if (T.isNull() ||
1407 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1408 continue;
1409
1410 Exceptions.push_back(T);
1411 }
1412
1413 // Rebuild the function type
1414
1415 const FunctionProtoType *NewProto
1416 = New->getType()->getAs<FunctionProtoType>();
1417 assert(NewProto && "Template instantiation without function prototype?");
1418 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1419 NewProto->arg_type_begin(),
1420 NewProto->getNumArgs(),
1421 NewProto->isVariadic(),
1422 NewProto->getTypeQuals(),
1423 Proto->hasExceptionSpec(),
1424 Proto->hasAnyExceptionSpec(),
1425 Exceptions.size(),
1426 Exceptions.data(),
1427 Proto->getNoReturnAttr()));
1428 }
1429
Douglas Gregore53060f2009-06-25 22:08:12 +00001430 return false;
1431}
1432
Douglas Gregor5545e162009-03-24 00:38:23 +00001433/// \brief Initializes common fields of an instantiated method
1434/// declaration (New) from the corresponding fields of its template
1435/// (Tmpl).
1436///
1437/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001438bool
1439TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001440 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001441 if (InitFunctionInstantiation(New, Tmpl))
1442 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregor5545e162009-03-24 00:38:23 +00001444 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1445 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001446 if (Tmpl->isVirtualAsWritten())
1447 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001448
1449 // FIXME: attributes
1450 // FIXME: New needs a pointer to Tmpl
1451 return false;
1452}
Douglas Gregora58861f2009-05-13 20:28:22 +00001453
1454/// \brief Instantiate the definition of the given function from its
1455/// template.
1456///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001457/// \param PointOfInstantiation the point at which the instantiation was
1458/// required. Note that this is not precisely a "point of instantiation"
1459/// for the function, but it's close.
1460///
Douglas Gregora58861f2009-05-13 20:28:22 +00001461/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001462/// function template specialization or member function of a class template
1463/// specialization.
1464///
1465/// \param Recursive if true, recursively instantiates any functions that
1466/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001467///
1468/// \param DefinitionRequired if true, then we are performing an explicit
1469/// instantiation where the body of the function is required. Complain if
1470/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001471void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001472 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001473 bool Recursive,
1474 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001475 if (Function->isInvalidDecl())
1476 return;
1477
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001478 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001480 // Never instantiate an explicit specialization.
1481 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1482 return;
1483
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001484 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001485 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001486 Stmt *Pattern = 0;
1487 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001488 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001489
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001490 if (!Pattern) {
1491 if (DefinitionRequired) {
1492 if (Function->getPrimaryTemplate())
1493 Diag(PointOfInstantiation,
1494 diag::err_explicit_instantiation_undefined_func_template)
1495 << Function->getPrimaryTemplate();
1496 else
1497 Diag(PointOfInstantiation,
1498 diag::err_explicit_instantiation_undefined_member)
1499 << 1 << Function->getDeclName() << Function->getDeclContext();
1500
1501 if (PatternDecl)
1502 Diag(PatternDecl->getLocation(),
1503 diag::note_explicit_instantiation_here);
1504 }
1505
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001506 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001507 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001508
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001509 // C++0x [temp.explicit]p9:
1510 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001511 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001512 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001513 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001514 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001515 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001516 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001518 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1519 if (Inst)
1520 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001521
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001522 // If we're performing recursive template instantiation, create our own
1523 // queue of pending implicit instantiations that we will instantiate later,
1524 // while we're still within our own instantiation context.
1525 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1526 if (Recursive)
1527 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001529 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1530
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001531 // Introduce a new scope where local variable instantiations will be
1532 // recorded.
1533 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001535 // Introduce the instantiated function parameters into the local
1536 // instantiation scope.
1537 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1538 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1539 Function->getParamDecl(I));
1540
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001541 // Enter the scope of this instantiation. We don't use
1542 // PushDeclContext because we don't have a scope.
1543 DeclContext *PreviousContext = CurContext;
1544 CurContext = Function;
1545
Mike Stump1eb44332009-09-09 15:08:12 +00001546 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001547 getTemplateInstantiationArgs(Function);
1548
1549 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001550 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001551 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1552 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1553 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001554 }
1555
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001556 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001557 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001558
Douglas Gregor52604ab2009-09-11 21:19:12 +00001559 if (Body.isInvalid())
1560 Function->setInvalidDecl();
1561
Mike Stump1eb44332009-09-09 15:08:12 +00001562 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001563 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001564
1565 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001566
1567 DeclGroupRef DG(Function);
1568 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001570 if (Recursive) {
1571 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001572 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001573 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001575 // Restore the set of pending implicit instantiations.
1576 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1577 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001578}
1579
1580/// \brief Instantiate the definition of the given variable from its
1581/// template.
1582///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001583/// \param PointOfInstantiation the point at which the instantiation was
1584/// required. Note that this is not precisely a "point of instantiation"
1585/// for the function, but it's close.
1586///
1587/// \param Var the already-instantiated declaration of a static member
1588/// variable of a class template specialization.
1589///
1590/// \param Recursive if true, recursively instantiates any functions that
1591/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001592///
1593/// \param DefinitionRequired if true, then we are performing an explicit
1594/// instantiation where an out-of-line definition of the member variable
1595/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001596void Sema::InstantiateStaticDataMemberDefinition(
1597 SourceLocation PointOfInstantiation,
1598 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001599 bool Recursive,
1600 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001601 if (Var->isInvalidDecl())
1602 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregor7caa6822009-07-24 20:34:43 +00001604 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001605 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001606 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001607 assert(Def->isStaticDataMember() && "Not a static data member?");
1608 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Douglas Gregor0d035142009-10-27 18:42:08 +00001610 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001611 // We did not find an out-of-line definition of this static data member,
1612 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001613 // instantiate this definition (or provide a specialization for it) in
1614 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001615 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001616 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001617 Diag(PointOfInstantiation,
1618 diag::err_explicit_instantiation_undefined_member)
1619 << 2 << Var->getDeclName() << Var->getDeclContext();
1620 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1621 }
1622
Douglas Gregor7caa6822009-07-24 20:34:43 +00001623 return;
1624 }
1625
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001626 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001627 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001628 return;
1629
1630 // C++0x [temp.explicit]p9:
1631 // Except for inline functions, other explicit instantiation declarations
1632 // have the effect of suppressing the implicit instantiation of the entity
1633 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001634 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001635 == TSK_ExplicitInstantiationDeclaration)
1636 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor7caa6822009-07-24 20:34:43 +00001638 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1639 if (Inst)
1640 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Douglas Gregor7caa6822009-07-24 20:34:43 +00001642 // If we're performing recursive template instantiation, create our own
1643 // queue of pending implicit instantiations that we will instantiate later,
1644 // while we're still within our own instantiation context.
1645 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1646 if (Recursive)
1647 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Douglas Gregor7caa6822009-07-24 20:34:43 +00001649 // Enter the scope of this instantiation. We don't use
1650 // PushDeclContext because we don't have a scope.
1651 DeclContext *PreviousContext = CurContext;
1652 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001654 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001655 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001656 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001657 CurContext = PreviousContext;
1658
1659 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001660 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001661 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1662 assert(MSInfo && "Missing member specialization information?");
1663 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1664 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001665 DeclGroupRef DG(Var);
1666 Consumer.HandleTopLevelDecl(DG);
1667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Douglas Gregor7caa6822009-07-24 20:34:43 +00001669 if (Recursive) {
1670 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001671 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001672 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Douglas Gregor7caa6822009-07-24 20:34:43 +00001674 // Restore the set of pending implicit instantiations.
1675 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001676 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001677}
Douglas Gregor815215d2009-05-27 05:35:12 +00001678
Anders Carlsson09025312009-08-29 05:16:22 +00001679void
1680Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1681 const CXXConstructorDecl *Tmpl,
1682 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Anders Carlsson09025312009-08-29 05:16:22 +00001684 llvm::SmallVector<MemInitTy*, 4> NewInits;
1685
1686 // Instantiate all the initializers.
1687 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001688 InitsEnd = Tmpl->init_end();
1689 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001690 CXXBaseOrMemberInitializer *Init = *Inits;
1691
1692 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Anders Carlsson09025312009-08-29 05:16:22 +00001694 // Instantiate all the arguments.
1695 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1696 Args != ArgsEnd; ++Args) {
1697 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1698
1699 if (NewArg.isInvalid())
1700 New->setInvalidDecl();
1701 else
1702 NewArgs.push_back(NewArg.takeAs<Expr>());
1703 }
1704
1705 MemInitResult NewInit;
1706
1707 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001708 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001709 TemplateArgs,
1710 Init->getSourceLocation(),
1711 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001712 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001713 New->setInvalidDecl();
1714 continue;
1715 }
1716
John McCalla93c9342009-12-07 02:54:59 +00001717 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001718 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001719 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001720 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001721 Init->getRParenLoc(),
1722 New->getParent());
1723 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001724 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001726 // Is this an anonymous union?
1727 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001728 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001729 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001730 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1731 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001732
1733 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001734 NewArgs.size(),
1735 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001736 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001737 Init->getRParenLoc());
1738 }
1739
1740 if (NewInit.isInvalid())
1741 New->setInvalidDecl();
1742 else {
1743 // FIXME: It would be nice if ASTOwningVector had a release function.
1744 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Anders Carlsson09025312009-08-29 05:16:22 +00001746 NewInits.push_back((MemInitTy *)NewInit.get());
1747 }
1748 }
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlsson09025312009-08-29 05:16:22 +00001750 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001751 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001752 /*FIXME: ColonLoc */
1753 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001754 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001755}
1756
John McCall52a575a2009-08-29 08:11:13 +00001757// TODO: this could be templated if the various decl types used the
1758// same method name.
1759static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1760 ClassTemplateDecl *Instance) {
1761 Pattern = Pattern->getCanonicalDecl();
1762
1763 do {
1764 Instance = Instance->getCanonicalDecl();
1765 if (Pattern == Instance) return true;
1766 Instance = Instance->getInstantiatedFromMemberTemplate();
1767 } while (Instance);
1768
1769 return false;
1770}
1771
Douglas Gregor0d696532009-09-28 06:34:35 +00001772static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1773 FunctionTemplateDecl *Instance) {
1774 Pattern = Pattern->getCanonicalDecl();
1775
1776 do {
1777 Instance = Instance->getCanonicalDecl();
1778 if (Pattern == Instance) return true;
1779 Instance = Instance->getInstantiatedFromMemberTemplate();
1780 } while (Instance);
1781
1782 return false;
1783}
1784
Douglas Gregored9c0f92009-10-29 00:04:11 +00001785static bool
1786isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1787 ClassTemplatePartialSpecializationDecl *Instance) {
1788 Pattern
1789 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1790 do {
1791 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1792 Instance->getCanonicalDecl());
1793 if (Pattern == Instance)
1794 return true;
1795 Instance = Instance->getInstantiatedFromMember();
1796 } while (Instance);
1797
1798 return false;
1799}
1800
John McCall52a575a2009-08-29 08:11:13 +00001801static bool isInstantiationOf(CXXRecordDecl *Pattern,
1802 CXXRecordDecl *Instance) {
1803 Pattern = Pattern->getCanonicalDecl();
1804
1805 do {
1806 Instance = Instance->getCanonicalDecl();
1807 if (Pattern == Instance) return true;
1808 Instance = Instance->getInstantiatedFromMemberClass();
1809 } while (Instance);
1810
1811 return false;
1812}
1813
1814static bool isInstantiationOf(FunctionDecl *Pattern,
1815 FunctionDecl *Instance) {
1816 Pattern = Pattern->getCanonicalDecl();
1817
1818 do {
1819 Instance = Instance->getCanonicalDecl();
1820 if (Pattern == Instance) return true;
1821 Instance = Instance->getInstantiatedFromMemberFunction();
1822 } while (Instance);
1823
1824 return false;
1825}
1826
1827static bool isInstantiationOf(EnumDecl *Pattern,
1828 EnumDecl *Instance) {
1829 Pattern = Pattern->getCanonicalDecl();
1830
1831 do {
1832 Instance = Instance->getCanonicalDecl();
1833 if (Pattern == Instance) return true;
1834 Instance = Instance->getInstantiatedFromMemberEnum();
1835 } while (Instance);
1836
1837 return false;
1838}
1839
John McCalled976492009-12-04 22:46:56 +00001840static bool isInstantiationOf(UsingShadowDecl *Pattern,
1841 UsingShadowDecl *Instance,
1842 ASTContext &C) {
1843 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1844}
1845
1846static bool isInstantiationOf(UsingDecl *Pattern,
1847 UsingDecl *Instance,
1848 ASTContext &C) {
1849 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1850}
1851
John McCall7ba107a2009-11-18 02:36:19 +00001852static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1853 UsingDecl *Instance,
1854 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001855 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001856}
1857
1858static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001859 UsingDecl *Instance,
1860 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001861 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001862}
1863
John McCall52a575a2009-08-29 08:11:13 +00001864static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1865 VarDecl *Instance) {
1866 assert(Instance->isStaticDataMember());
1867
1868 Pattern = Pattern->getCanonicalDecl();
1869
1870 do {
1871 Instance = Instance->getCanonicalDecl();
1872 if (Pattern == Instance) return true;
1873 Instance = Instance->getInstantiatedFromStaticDataMember();
1874 } while (Instance);
1875
1876 return false;
1877}
1878
John McCalled976492009-12-04 22:46:56 +00001879// Other is the prospective instantiation
1880// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001881static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001882 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001883 if (UnresolvedUsingTypenameDecl *UUD
1884 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1885 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1886 return isInstantiationOf(UUD, UD, Ctx);
1887 }
1888 }
1889
1890 if (UnresolvedUsingValueDecl *UUD
1891 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001892 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1893 return isInstantiationOf(UUD, UD, Ctx);
1894 }
1895 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001896
Anders Carlsson0d8df782009-08-29 19:37:28 +00001897 return false;
1898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
John McCall52a575a2009-08-29 08:11:13 +00001900 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1901 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001902
John McCall52a575a2009-08-29 08:11:13 +00001903 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1904 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001905
John McCall52a575a2009-08-29 08:11:13 +00001906 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1907 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001908
Douglas Gregor7caa6822009-07-24 20:34:43 +00001909 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001910 if (Var->isStaticDataMember())
1911 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1912
1913 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1914 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001915
Douglas Gregor0d696532009-09-28 06:34:35 +00001916 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1917 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1918
Douglas Gregored9c0f92009-10-29 00:04:11 +00001919 if (ClassTemplatePartialSpecializationDecl *PartialSpec
1920 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
1921 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
1922 PartialSpec);
1923
Anders Carlssond8b285f2009-09-01 04:26:58 +00001924 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1925 if (!Field->getDeclName()) {
1926 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00001927 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00001928 cast<FieldDecl>(D);
1929 }
1930 }
Mike Stump1eb44332009-09-09 15:08:12 +00001931
John McCalled976492009-12-04 22:46:56 +00001932 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
1933 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
1934
1935 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
1936 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
1937
Douglas Gregor815215d2009-05-27 05:35:12 +00001938 return D->getDeclName() && isa<NamedDecl>(Other) &&
1939 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1940}
1941
1942template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00001943static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00001944 NamedDecl *D,
1945 ForwardIterator first,
1946 ForwardIterator last) {
1947 for (; first != last; ++first)
1948 if (isInstantiationOf(Ctx, D, *first))
1949 return cast<NamedDecl>(*first);
1950
1951 return 0;
1952}
1953
John McCall02cace72009-08-28 07:59:38 +00001954/// \brief Finds the instantiation of the given declaration context
1955/// within the current instantiation.
1956///
1957/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00001958DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1959 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00001960 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00001961 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00001962 return cast_or_null<DeclContext>(ID);
1963 } else return DC;
1964}
1965
Douglas Gregored961e72009-05-27 17:54:46 +00001966/// \brief Find the instantiation of the given declaration within the
1967/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001968///
1969/// This routine is intended to be used when \p D is a declaration
1970/// referenced from within a template, that needs to mapped into the
1971/// corresponding declaration within an instantiation. For example,
1972/// given:
1973///
1974/// \code
1975/// template<typename T>
1976/// struct X {
1977/// enum Kind {
1978/// KnownValue = sizeof(T)
1979/// };
1980///
1981/// bool getKind() const { return KnownValue; }
1982/// };
1983///
1984/// template struct X<int>;
1985/// \endcode
1986///
1987/// In the instantiation of X<int>::getKind(), we need to map the
1988/// EnumConstantDecl for KnownValue (which refers to
1989/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001990/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1991/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00001992NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1993 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001994 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00001995 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
1996 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
1997 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001998 // D is a local of some kind. Look into the map of local
1999 // declarations to their instantiations.
2000 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2001 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002002
Douglas Gregore95b4092009-09-16 18:34:49 +00002003 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2004 if (!Record->isDependentContext())
2005 return D;
2006
2007 // If the RecordDecl is actually the injected-class-name or a "templated"
2008 // declaration for a class template or class template partial
2009 // specialization, substitute into the injected-class-name of the
2010 // class template or partial specialization to find the new DeclContext.
2011 QualType T;
2012 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2013
2014 if (ClassTemplate) {
2015 T = ClassTemplate->getInjectedClassNameType(Context);
2016 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2017 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2018 T = Context.getTypeDeclType(Record);
2019 ClassTemplate = PartialSpec->getSpecializedTemplate();
2020 }
2021
2022 if (!T.isNull()) {
2023 // Substitute into the injected-class-name to get the type corresponding
2024 // to the instantiation we want. This substitution should never fail,
2025 // since we know we can instantiate the injected-class-name or we wouldn't
2026 // have gotten to the injected-class-name!
2027 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2028 // instantiation in the common case?
2029 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2030 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2031
2032 if (!T->isDependentType()) {
2033 assert(T->isRecordType() && "Instantiation must produce a record type");
2034 return T->getAs<RecordType>()->getDecl();
2035 }
2036
2037 // We are performing "partial" template instantiation to create the
2038 // member declarations for the members of a class template
2039 // specialization. Therefore, D is actually referring to something in
2040 // the current instantiation. Look through the current context,
2041 // which contains actual instantiations, to find the instantiation of
2042 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002043 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002044 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002045 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002046 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002047 if (isInstantiationOf(ClassTemplate,
2048 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002049 return Spec;
2050 }
2051
Mike Stump1eb44332009-09-09 15:08:12 +00002052 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002053 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002054 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002055 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002056
2057 // Fall through to deal with other dependent record types (e.g.,
2058 // anonymous unions in class templates).
2059 }
John McCall52a575a2009-08-29 08:11:13 +00002060
Douglas Gregore95b4092009-09-16 18:34:49 +00002061 if (!ParentDC->isDependentContext())
2062 return D;
2063
2064 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002065 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002066 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Douglas Gregor815215d2009-05-27 05:35:12 +00002068 if (ParentDC != D->getDeclContext()) {
2069 // We performed some kind of instantiation in the parent context,
2070 // so now we need to look into the instantiated parent context to
2071 // find the instantiation of the declaration D.
2072 NamedDecl *Result = 0;
2073 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002074 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002075 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2076 } else {
2077 // Since we don't have a name for the entity we're looking for,
2078 // our only option is to walk through all of the declarations to
2079 // find that name. This will occur in a few cases:
2080 //
2081 // - anonymous struct/union within a template
2082 // - unnamed class/struct/union/enum within a template
2083 //
2084 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002085 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002086 ParentDC->decls_begin(),
2087 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002088 }
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregor815215d2009-05-27 05:35:12 +00002090 assert(Result && "Unable to find instantiation of declaration!");
2091 D = Result;
2092 }
2093
Douglas Gregor815215d2009-05-27 05:35:12 +00002094 return D;
2095}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002096
Mike Stump1eb44332009-09-09 15:08:12 +00002097/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002098/// instantiations we have seen until this point.
2099void Sema::PerformPendingImplicitInstantiations() {
2100 while (!PendingImplicitInstantiations.empty()) {
2101 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002102 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Douglas Gregor7caa6822009-07-24 20:34:43 +00002104 // Instantiate function definitions
2105 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002106 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002107 Function->getLocation(), *this,
2108 Context.getSourceManager(),
2109 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002111 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002112 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002113 continue;
2114 }
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Douglas Gregor7caa6822009-07-24 20:34:43 +00002116 // Instantiate static data member definitions.
2117 VarDecl *Var = cast<VarDecl>(Inst.first);
2118 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002119
Mike Stump1eb44332009-09-09 15:08:12 +00002120 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002121 Var->getLocation(), *this,
2122 Context.getSourceManager(),
2123 "instantiating static data member "
2124 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Douglas Gregor7caa6822009-07-24 20:34:43 +00002126 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002127 }
2128}