blob: 3f40ffcdc17817883a69d0c58502f0005b55caf2 [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#include "llvm/Support/Compiler.h"
22
23using namespace clang;
24
25namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000026 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000027 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028 Sema &SemaRef;
29 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000030 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Anders Carlssond8fe2d52009-11-07 06:07:58 +000032 void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
43 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000046 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000047 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitFieldDecl(FieldDecl *D);
49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000052 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000053 Decl *VisitFunctionDecl(FunctionDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000055 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000056 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000058 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000059 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000060 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000061 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000062 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000063 Decl *VisitClassTemplatePartialSpecializationDecl(
64 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000065 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000067 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000068 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000069 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000070 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
71 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor8dbc2692009-03-17 21:15:40 +000073 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000074 Decl *VisitDecl(Decl *D) {
75 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
76 Diagnostic::Error,
77 "cannot instantiate %0 yet");
78 SemaRef.Diag(D->getLocation(), DiagID)
79 << D->getDeclKindName();
80
Douglas Gregor8dbc2692009-03-17 21:15:40 +000081 return 0;
82 }
Douglas Gregor5545e162009-03-24 00:38:23 +000083
John McCallfd810b12009-08-14 02:03:10 +000084 const LangOptions &getLangOptions() {
85 return SemaRef.getLangOptions();
86 }
87
Douglas Gregor5545e162009-03-24 00:38:23 +000088 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000089 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000090 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000091 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000092 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000093
94 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000095 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000096
97 bool InstantiateClassTemplatePartialSpecialization(
98 ClassTemplateDecl *ClassTemplate,
99 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000100 };
101}
102
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000103// FIXME: Is this too simple?
104void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
105 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
106 TmplAttr = TmplAttr->getNext()) {
107
108 // FIXME: Is cloning correct for all attributes?
109 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
110
111 New->addAttr(NewAttr);
112 }
113}
114
Douglas Gregor4f722be2009-03-25 15:45:12 +0000115Decl *
116TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
117 assert(false && "Translation units cannot be instantiated");
118 return D;
119}
120
121Decl *
122TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
123 assert(false && "Namespaces cannot be instantiated");
124 return D;
125}
126
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000127Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
128 bool Invalid = false;
John McCallba6a9bd2009-10-24 08:00:42 +0000129 DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
130 if (DI->getType()->isDependentType()) {
131 DI = SemaRef.SubstType(DI, TemplateArgs,
132 D->getLocation(), D->getDeclName());
133 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000134 Invalid = true;
John McCallba6a9bd2009-10-24 08:00:42 +0000135 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000136 }
137 }
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000139 // Create the new typedef
140 TypedefDecl *Typedef
141 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000142 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000143 if (Invalid)
144 Typedef->setInvalidDecl();
145
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000146 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000148 return Typedef;
149}
150
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000151Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000152 // Do substitution on the type of the declaration
John McCall0a5fa062009-10-21 02:39:02 +0000153 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(),
154 TemplateArgs,
155 D->getTypeSpecStartLoc(),
156 D->getDeclName());
157 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000158 return 0;
159
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000160 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000161 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
162 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000163 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000164 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000165 Var->setThreadSpecified(D->isThreadSpecified());
166 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
167 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000168
169 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000170 // out-of-line, the instantiation will have the same lexical
171 // context (which will be a namespace scope) as the template.
172 if (D->isOutOfLine())
173 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Mike Stump390b4cc2009-05-16 07:39:55 +0000175 // FIXME: In theory, we could have a previous declaration for variables that
176 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000177 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000178 // FIXME: having to fake up a LookupResult is dumb.
179 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
180 Sema::LookupOrdinaryName);
181 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Douglas Gregor7caa6822009-07-24 20:34:43 +0000183 if (D->isOutOfLine()) {
184 D->getLexicalDeclContext()->addDecl(Var);
185 Owner->makeDeclVisibleInContext(Var);
186 } else {
187 Owner->addDecl(Var);
188 }
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000190 // Link instantiations of static data members back to the template from
191 // which they were instantiated.
192 if (Var->isStaticDataMember())
193 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000194 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000195
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000196 if (D->getInit()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000197 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000198 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000199 if (Init.isInvalid())
200 Var->setInvalidDecl();
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000201 else if (!D->getType()->isDependentType() &&
202 !D->getInit()->isTypeDependent() &&
Douglas Gregore48319a2009-11-09 17:16:50 +0000203 !D->getInit()->isValueDependent()) {
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000204 // If neither the declaration's type nor its initializer are dependent,
205 // we don't want to redo all the checking, especially since the
206 // initializer might have been wrapped by a CXXConstructExpr since we did
207 // it the first time.
208 Var->setInit(SemaRef.Context, Init.takeAs<Expr>());
209 }
Douglas Gregor83ddad32009-08-26 21:14:46 +0000210 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000211 // FIXME: We're faking all of the comma locations, which is suboptimal.
Douglas Gregor83ddad32009-08-26 21:14:46 +0000212 // Do we even need these comma locations?
213 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
214 if (PLE->getNumExprs() > 0) {
215 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
216 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
217 Expr *E = PLE->getExpr(I)->Retain();
218 FakeCommaLocs.push_back(
219 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
220 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000221 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Douglas Gregor83ddad32009-08-26 21:14:46 +0000224 // Add the direct initializer to the declaration.
225 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Mike Stump1eb44332009-09-09 15:08:12 +0000226 PLE->getLParenLoc(),
Douglas Gregor83ddad32009-08-26 21:14:46 +0000227 Sema::MultiExprArg(SemaRef,
228 (void**)PLE->getExprs(),
229 PLE->getNumExprs()),
230 FakeCommaLocs.data(),
231 PLE->getRParenLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Douglas Gregor83ddad32009-08-26 21:14:46 +0000233 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
234 // we've explicitly retained all of its subexpressions already.
235 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000236 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000237 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000238 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
239 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000240
241 return Var;
242}
243
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000244Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
245 bool Invalid = false;
John McCall07fb6be2009-10-22 23:33:21 +0000246 DeclaratorInfo *DI = D->getDeclaratorInfo();
247 if (DI->getType()->isDependentType()) {
248 DI = SemaRef.SubstType(DI, TemplateArgs,
249 D->getLocation(), D->getDeclName());
250 if (!DI) {
251 DI = D->getDeclaratorInfo();
252 Invalid = true;
253 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000254 // C++ [temp.arg.type]p3:
255 // If a declaration acquires a function type through a type
256 // dependent on a template-parameter and this causes a
257 // declaration that does not use the syntactic form of a
258 // function declarator to have function type, the program is
259 // ill-formed.
260 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000261 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000262 Invalid = true;
263 }
264 }
265
266 Expr *BitWidth = D->getBitWidth();
267 if (Invalid)
268 BitWidth = 0;
269 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000270 // The bit-width expression is not potentially evaluated.
271 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000273 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000274 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000275 if (InstantiatedBitWidth.isInvalid()) {
276 Invalid = true;
277 BitWidth = 0;
278 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000279 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000280 }
281
John McCall07fb6be2009-10-22 23:33:21 +0000282 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
283 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000284 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000285 D->getLocation(),
286 D->isMutable(),
287 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000288 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000289 D->getAccess(),
290 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000291 if (!Field) {
292 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000293 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000294 }
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000296 InstantiateAttrs(D, Field);
297
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000298 if (Invalid)
299 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000301 if (!Field->getDeclName()) {
302 // Keep track of where this decl came from.
303 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000304 }
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000306 Field->setImplicit(D->isImplicit());
307 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000308
309 return Field;
310}
311
John McCall02cace72009-08-28 07:59:38 +0000312Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
313 FriendDecl::FriendUnion FU;
314
315 // Handle friend type expressions by simply substituting template
316 // parameters into the pattern type.
317 if (Type *Ty = D->getFriendType()) {
318 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
319 D->getLocation(), DeclarationName());
320 if (T.isNull()) return 0;
321
322 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
323 FU = T.getTypePtr();
324
325 // Handle everything else by appropriate substitution.
326 } else {
327 NamedDecl *ND = D->getFriendDecl();
328 assert(ND && "friend decl must be a decl or a type!");
329
Douglas Gregora735b202009-10-13 14:39:41 +0000330 // FIXME: We have a problem here, because the nested call to Visit(ND)
331 // will inject the thing that the friend references into the current
332 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000333 Decl *NewND = Visit(ND);
334 if (!NewND) return 0;
335
336 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
John McCall02cace72009-08-28 07:59:38 +0000339 FriendDecl *FD =
340 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
341 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000342 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000343 Owner->addDecl(FD);
344 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000345}
346
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000347Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
348 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Douglas Gregorac7610d2009-06-22 20:57:11 +0000350 // The expression in a static assertion is not potentially evaluated.
351 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000353 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000354 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000355 if (InstantiatedAssertExpr.isInvalid())
356 return 0;
357
Douglas Gregor43d9d922009-08-08 01:41:12 +0000358 OwningExprResult Message(SemaRef, D->getMessage());
359 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000360 Decl *StaticAssert
361 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000362 move(InstantiatedAssertExpr),
363 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000364 return StaticAssert;
365}
366
367Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000368 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000369 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000370 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000371 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000372 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000373 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000374 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000375 Enum->startDefinition();
376
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000377 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000378
379 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000380 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
381 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000382 EC != ECEnd; ++EC) {
383 // The specified value for the enumerator.
384 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000385 if (Expr *UninstValue = EC->getInitExpr()) {
386 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000387 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000388 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000389
John McCallce3ff2b2009-08-25 22:02:44 +0000390 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000391 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000392
393 // Drop the initial value and continue.
394 bool isInvalid = false;
395 if (Value.isInvalid()) {
396 Value = SemaRef.Owned((Expr *)0);
397 isInvalid = true;
398 }
399
Mike Stump1eb44332009-09-09 15:08:12 +0000400 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000401 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
402 EC->getLocation(), EC->getIdentifier(),
403 move(Value));
404
405 if (isInvalid) {
406 if (EnumConst)
407 EnumConst->setInvalidDecl();
408 Enum->setInvalidDecl();
409 }
410
411 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000412 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000413 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000414 LastEnumConst = EnumConst;
415 }
416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000418 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000419 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000420 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
421 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000422 &Enumerators[0], Enumerators.size(),
423 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000424
425 return Enum;
426}
427
Douglas Gregor6477b692009-03-25 15:04:13 +0000428Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
429 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
430 return 0;
431}
432
Douglas Gregored9c0f92009-10-29 00:04:11 +0000433namespace {
434 class SortDeclByLocation {
435 SourceManager &SourceMgr;
436
437 public:
438 explicit SortDeclByLocation(SourceManager &SourceMgr)
439 : SourceMgr(SourceMgr) { }
440
441 bool operator()(const Decl *X, const Decl *Y) const {
442 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
443 Y->getLocation());
444 }
445 };
446}
447
John McCalle29ba202009-08-20 01:44:21 +0000448Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000449 // Create a local instantiation scope for this class template, which
450 // will contain the instantiations of the template parameters.
451 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000452 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000453 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000454 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000455 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000456
457 CXXRecordDecl *Pattern = D->getTemplatedDecl();
458 CXXRecordDecl *RecordInst
459 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
460 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000461 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
462 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000463
464 ClassTemplateDecl *Inst
465 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
466 D->getIdentifier(), InstParams, RecordInst, 0);
467 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000468 if (D->getFriendObjectKind())
469 Inst->setObjectOfFriendDecl(true);
470 else
471 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000472 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000473
474 // Trigger creation of the type for the instantiation.
475 SemaRef.Context.getTypeDeclType(RecordInst);
476
Douglas Gregor259571e2009-10-30 22:42:42 +0000477 // Finish handling of friends.
478 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000479 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000480 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000481
John McCalle29ba202009-08-20 01:44:21 +0000482 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000483
484 // First, we sort the partial specializations by location, so
485 // that we instantiate them in the order they were declared.
486 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
487 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
488 P = D->getPartialSpecializations().begin(),
489 PEnd = D->getPartialSpecializations().end();
490 P != PEnd; ++P)
491 PartialSpecs.push_back(&*P);
492 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
493 SortDeclByLocation(SemaRef.SourceMgr));
494
495 // Instantiate all of the partial specializations of this member class
496 // template.
497 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
498 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
499
John McCalle29ba202009-08-20 01:44:21 +0000500 return Inst;
501}
502
Douglas Gregord60e1052009-08-27 16:57:43 +0000503Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000504TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
505 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000506 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
507
508 // Lookup the already-instantiated declaration in the instantiation
509 // of the class template and return that.
510 DeclContext::lookup_result Found
511 = Owner->lookup(ClassTemplate->getDeclName());
512 if (Found.first == Found.second)
513 return 0;
514
515 ClassTemplateDecl *InstClassTemplate
516 = dyn_cast<ClassTemplateDecl>(*Found.first);
517 if (!InstClassTemplate)
518 return 0;
519
520 Decl *DCanon = D->getCanonicalDecl();
521 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
522 P = InstClassTemplate->getPartialSpecializations().begin(),
523 PEnd = InstClassTemplate->getPartialSpecializations().end();
524 P != PEnd; ++P) {
525 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
526 return &*P;
527 }
528
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000529 return 0;
530}
531
532Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000533TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000534 // Create a local instantiation scope for this function template, which
535 // will contain the instantiations of the template parameters and then get
536 // merged with the local instantiation scope for the function template
537 // itself.
538 Sema::LocalInstantiationScope Scope(SemaRef);
539
Douglas Gregord60e1052009-08-27 16:57:43 +0000540 TemplateParameterList *TempParams = D->getTemplateParameters();
541 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000542 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000543 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000544
Douglas Gregora735b202009-10-13 14:39:41 +0000545 FunctionDecl *Instantiated = 0;
546 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
547 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
548 InstParams));
549 else
550 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
551 D->getTemplatedDecl(),
552 InstParams));
553
554 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000555 return 0;
556
Mike Stump1eb44332009-09-09 15:08:12 +0000557 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000558 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000559 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000560 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000561 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000562 assert(InstTemplate &&
563 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
564 if (!InstTemplate->getInstantiatedFromMemberTemplate())
565 InstTemplate->setInstantiatedFromMemberTemplate(D);
566
567 // Add non-friends into the owner.
568 if (!InstTemplate->getFriendObjectKind())
569 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000570 return InstTemplate;
571}
572
Douglas Gregord475b8d2009-03-25 21:17:03 +0000573Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
574 CXXRecordDecl *PrevDecl = 0;
575 if (D->isInjectedClassName())
576 PrevDecl = cast<CXXRecordDecl>(Owner);
577
578 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000579 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000580 D->getLocation(), D->getIdentifier(),
581 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000582 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000583 // FIXME: Check against AS_none is an ugly hack to work around the issue that
584 // the tag decls introduced by friend class declarations don't have an access
585 // specifier. Remove once this area of the code gets sorted out.
586 if (D->getAccess() != AS_none)
587 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000588 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000589 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000590
John McCall02cace72009-08-28 07:59:38 +0000591 // If the original function was part of a friend declaration,
592 // inherit its namespace state.
593 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
594 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
595
Anders Carlssond8b285f2009-09-01 04:26:58 +0000596 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
597
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000598 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000599 return Record;
600}
601
John McCall02cace72009-08-28 07:59:38 +0000602/// Normal class members are of more specific types and therefore
603/// don't make it here. This function serves two purposes:
604/// 1) instantiating function templates
605/// 2) substituting friend declarations
606/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000607 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
608 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000609 // Check whether there is already a function template specialization for
610 // this declaration.
611 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
612 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000613 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000614 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000615 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000616 TemplateArgs.getInnermost().getFlatArgumentList(),
617 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000618 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000619
620 FunctionTemplateSpecializationInfo *Info
621 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000622 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Douglas Gregor127102b2009-06-29 20:59:39 +0000624 // If we already have a function template specialization, return it.
625 if (Info)
626 return Info->Function;
627 }
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Douglas Gregor550d9b22009-10-31 17:21:17 +0000629 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregore53060f2009-06-25 22:08:12 +0000631 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000632 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000633 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000634 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000635
Douglas Gregore53060f2009-06-25 22:08:12 +0000636 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000637 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
638 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000639 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000640 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000641 D->getDeclName(), T, D->getDeclaratorInfo(),
642 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000643 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000644 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Douglas Gregore53060f2009-06-25 22:08:12 +0000646 // Attach the parameters
647 for (unsigned P = 0; P < Params.size(); ++P)
648 Params[P]->setOwningFunction(Function);
649 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000650
Douglas Gregora735b202009-10-13 14:39:41 +0000651 if (TemplateParams) {
652 // Our resulting instantiation is actually a function template, since we
653 // are substituting only the outer template parameters. For example, given
654 //
655 // template<typename T>
656 // struct X {
657 // template<typename U> friend void f(T, U);
658 // };
659 //
660 // X<int> x;
661 //
662 // We are instantiating the friend function template "f" within X<int>,
663 // which means substituting int for T, but leaving "f" as a friend function
664 // template.
665 // Build the function template itself.
666 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
667 Function->getLocation(),
668 Function->getDeclName(),
669 TemplateParams, Function);
670 Function->setDescribedFunctionTemplate(FunctionTemplate);
671 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000672 } else if (FunctionTemplate) {
673 // Record this function template specialization.
674 Function->setFunctionTemplateSpecialization(SemaRef.Context,
675 FunctionTemplate,
676 &TemplateArgs.getInnermost(),
677 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000678 }
Douglas Gregora735b202009-10-13 14:39:41 +0000679
Douglas Gregore53060f2009-06-25 22:08:12 +0000680 if (InitFunctionInstantiation(Function, D))
681 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Douglas Gregore53060f2009-06-25 22:08:12 +0000683 bool Redeclaration = false;
684 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000685
John McCall68263142009-11-18 22:49:29 +0000686 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
687 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
688
Douglas Gregora735b202009-10-13 14:39:41 +0000689 if (TemplateParams || !FunctionTemplate) {
690 // Look only into the namespace where the friend would be declared to
691 // find a previous declaration. This is the innermost enclosing namespace,
692 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000693 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000694
Douglas Gregora735b202009-10-13 14:39:41 +0000695 // In C++, the previous declaration we find might be a tag type
696 // (class or enum). In this case, the new declaration will hide the
697 // tag type. Note that this does does not apply if we're declaring a
698 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000699 if (Previous.isSingleTagDecl())
700 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000701 }
702
John McCall68263142009-11-18 22:49:29 +0000703 SemaRef.CheckFunctionDeclaration(Function, Previous, false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000704 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000705
Douglas Gregora735b202009-10-13 14:39:41 +0000706 // If the original function was part of a friend declaration,
707 // inherit its namespace state and add it to the owner.
708 NamedDecl *FromFriendD
709 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
710 if (FromFriendD->getFriendObjectKind()) {
711 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000712 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000713 if (TemplateParams) {
714 ToFriendD = cast<NamedDecl>(FunctionTemplate);
715 PrevDecl = FunctionTemplate->getPreviousDeclaration();
716 } else {
717 ToFriendD = Function;
718 PrevDecl = Function->getPreviousDeclaration();
719 }
720 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
721 if (!Owner->isDependentContext() && !PrevDecl)
722 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
723
724 if (!TemplateParams)
725 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
726 }
727
Douglas Gregore53060f2009-06-25 22:08:12 +0000728 return Function;
729}
730
Douglas Gregord60e1052009-08-27 16:57:43 +0000731Decl *
732TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
733 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000734 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
735 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000736 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000737 // We are creating a function template specialization from a function
738 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000739 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000740 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000741 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000742 TemplateArgs.getInnermost().getFlatArgumentList(),
743 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000744 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
746 FunctionTemplateSpecializationInfo *Info
747 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000748 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Douglas Gregor6b906862009-08-21 00:16:32 +0000750 // If we already have a function template specialization, return it.
751 if (Info)
752 return Info->Function;
753 }
754
Douglas Gregor550d9b22009-10-31 17:21:17 +0000755 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000756
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000757 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000758 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000759 if (T.isNull())
760 return 0;
761
762 // Build the instantiated method declaration.
763 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000764 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregordec06662009-08-21 18:42:58 +0000766 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000767 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000768 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
769 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
770 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000771 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
772 Constructor->getLocation(),
773 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000774 Constructor->getDeclaratorInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000775 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000776 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000777 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
778 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
779 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
780 SemaRef.Context.getCanonicalType(ClassTy));
781 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
782 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000783 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000784 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000785 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000786 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000787 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000788 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
789 ConvTy);
790 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
791 Conversion->getLocation(), Name,
792 T, Conversion->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000793 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000794 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000795 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000796 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000797 D->getDeclName(), T, D->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000798 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000799 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000800
Douglas Gregord60e1052009-08-27 16:57:43 +0000801 if (TemplateParams) {
802 // Our resulting instantiation is actually a function template, since we
803 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000804 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000805 // template<typename T>
806 // struct X {
807 // template<typename U> void f(T, U);
808 // };
809 //
810 // X<int> x;
811 //
812 // We are instantiating the member template "f" within X<int>, which means
813 // substituting int for T, but leaving "f" as a member function template.
814 // Build the function template itself.
815 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
816 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000817 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000818 TemplateParams, Method);
819 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000820 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000821 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000822 } else if (FunctionTemplate) {
823 // Record this function template specialization.
824 Method->setFunctionTemplateSpecialization(SemaRef.Context,
825 FunctionTemplate,
826 &TemplateArgs.getInnermost(),
827 InsertPos);
828 } else {
829 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000830 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000831 }
832
Mike Stump1eb44332009-09-09 15:08:12 +0000833 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000834 // out-of-line, the instantiation will have the same lexical
835 // context (which will be a namespace scope) as the template.
836 if (D->isOutOfLine())
837 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Douglas Gregor5545e162009-03-24 00:38:23 +0000839 // Attach the parameters
840 for (unsigned P = 0; P < Params.size(); ++P)
841 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000842 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000843
844 if (InitMethodInstantiation(Method, D))
845 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000846
John McCall68263142009-11-18 22:49:29 +0000847 LookupResult Previous(SemaRef, Name, SourceLocation(),
848 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregord60e1052009-08-27 16:57:43 +0000850 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000851 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregordec06662009-08-21 18:42:58 +0000853 // In C++, the previous declaration we find might be a tag type
854 // (class or enum). In this case, the new declaration will hide the
855 // tag type. Note that this does does not apply if we're declaring a
856 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000857 if (Previous.isSingleTagDecl())
858 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000859 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000860
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000861 bool Redeclaration = false;
862 bool OverloadableAttrRequired = false;
John McCall68263142009-11-18 22:49:29 +0000863 SemaRef.CheckFunctionDeclaration(Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000864 /*FIXME:*/OverloadableAttrRequired);
865
John McCall68263142009-11-18 22:49:29 +0000866 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000867 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000868 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Sebastian Redla165da02009-11-18 21:51:29 +0000870 SemaRef.AddOverriddenMethods(Record, Method);
871
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000872 return Method;
873}
874
Douglas Gregor615c5d42009-03-24 16:43:20 +0000875Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000876 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000877}
878
Douglas Gregor03b2b072009-03-24 00:15:49 +0000879Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000880 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000881}
882
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000883Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000884 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000885}
886
Douglas Gregor6477b692009-03-25 15:04:13 +0000887ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000888 QualType T;
889 DeclaratorInfo *DI = D->getDeclaratorInfo();
890 if (DI) {
891 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
892 D->getDeclName());
893 if (DI) T = DI->getType();
894 } else {
895 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
896 D->getDeclName());
897 DI = 0;
898 }
899
900 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000901 return 0;
902
John McCall58e46772009-10-23 21:48:59 +0000903 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000904
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000905 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000906 ParmVarDecl *Param
907 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
908 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000909
Anders Carlsson9351c172009-08-25 03:18:48 +0000910 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000911 if (D->hasUninstantiatedDefaultArg())
912 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000913 else if (Expr *Arg = D->getDefaultArg())
914 Param->setUninstantiatedDefaultArg(Arg);
915
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000916 // Note: we don't try to instantiate function parameters until after
917 // we've instantiated the function's type. Therefore, we don't have
918 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000919 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000920 return Param;
921}
922
John McCalle29ba202009-08-20 01:44:21 +0000923Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
924 TemplateTypeParmDecl *D) {
925 // TODO: don't always clone when decls are refcounted.
926 const Type* T = D->getTypeForDecl();
927 assert(T->isTemplateTypeParmType());
928 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000929
John McCalle29ba202009-08-20 01:44:21 +0000930 TemplateTypeParmDecl *Inst =
931 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +0000932 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +0000933 TTPT->getName(),
934 D->wasDeclaredWithTypename(),
935 D->isParameterPack());
936
Douglas Gregor0f8716b2009-11-09 19:17:50 +0000937 if (D->hasDefaultArgument())
938 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +0000939
Douglas Gregor550d9b22009-10-31 17:21:17 +0000940 // Introduce this template parameter's instantiation into the instantiation
941 // scope.
942 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
943
John McCalle29ba202009-08-20 01:44:21 +0000944 return Inst;
945}
946
Douglas Gregor33642df2009-10-23 23:25:44 +0000947Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
948 NonTypeTemplateParmDecl *D) {
949 // Substitute into the type of the non-type template parameter.
950 QualType T;
951 DeclaratorInfo *DI = D->getDeclaratorInfo();
952 if (DI) {
953 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
954 D->getDeclName());
955 if (DI) T = DI->getType();
956 } else {
957 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
958 D->getDeclName());
959 DI = 0;
960 }
961 if (T.isNull())
962 return 0;
963
964 // Check that this type is acceptable for a non-type template parameter.
965 bool Invalid = false;
966 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
967 if (T.isNull()) {
968 T = SemaRef.Context.IntTy;
969 Invalid = true;
970 }
971
972 NonTypeTemplateParmDecl *Param
973 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
974 D->getDepth() - 1, D->getPosition(),
975 D->getIdentifier(), T, DI);
976 if (Invalid)
977 Param->setInvalidDecl();
978
979 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +0000980
981 // Introduce this template parameter's instantiation into the instantiation
982 // scope.
983 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +0000984 return Param;
985}
986
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000987Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +0000988TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
989 TemplateTemplateParmDecl *D) {
990 // Instantiate the template parameter list of the template template parameter.
991 TemplateParameterList *TempParams = D->getTemplateParameters();
992 TemplateParameterList *InstParams;
993 {
994 // Perform the actual substitution of template parameters within a new,
995 // local instantiation scope.
996 Sema::LocalInstantiationScope Scope(SemaRef);
997 InstParams = SubstTemplateParams(TempParams);
998 if (!InstParams)
999 return NULL;
1000 }
1001
1002 // Build the template template parameter.
1003 TemplateTemplateParmDecl *Param
1004 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1005 D->getDepth() - 1, D->getPosition(),
1006 D->getIdentifier(), InstParams);
1007 Param->setDefaultArgument(D->getDefaultArgument());
1008
1009 // Introduce this template parameter's instantiation into the instantiation
1010 // scope.
1011 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1012
1013 return Param;
1014}
1015
Douglas Gregor48c32a72009-11-17 06:07:40 +00001016Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1017 // Using directives are never dependent, so they require no explicit
1018
1019 UsingDirectiveDecl *Inst
1020 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1021 D->getNamespaceKeyLocation(),
1022 D->getQualifierRange(), D->getQualifier(),
1023 D->getIdentLocation(),
1024 D->getNominatedNamespace(),
1025 D->getCommonAncestor());
1026 Owner->addDecl(Inst);
1027 return Inst;
1028}
1029
John McCall7ba107a2009-11-18 02:36:19 +00001030Decl * TemplateDeclInstantiator
1031 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001032 NestedNameSpecifier *NNS =
1033 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1034 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001035 TemplateArgs);
1036 if (!NNS)
1037 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001039 CXXScopeSpec SS;
1040 SS.setRange(D->getTargetNestedNameRange());
1041 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001042
1043 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001044 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001045 D->getUsingLoc(), SS, D->getLocation(),
1046 D->getDeclName(), 0,
1047 /*instantiation*/ true,
1048 /*typename*/ true, D->getTypenameLoc());
1049 if (UD)
1050 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
1051 D);
1052 return UD;
1053}
1054
1055Decl * TemplateDeclInstantiator
1056 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1057 NestedNameSpecifier *NNS =
1058 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1059 D->getTargetNestedNameRange(),
1060 TemplateArgs);
1061 if (!NNS)
1062 return 0;
1063
1064 CXXScopeSpec SS;
1065 SS.setRange(D->getTargetNestedNameRange());
1066 SS.setScopeRep(NNS);
1067
1068 NamedDecl *UD =
1069 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1070 D->getUsingLoc(), SS, D->getLocation(),
1071 D->getDeclName(), 0,
1072 /*instantiation*/ true,
1073 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001074 if (UD)
Mike Stump1eb44332009-09-09 15:08:12 +00001075 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
Anders Carlsson0d8df782009-08-29 19:37:28 +00001076 D);
1077 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001078}
1079
John McCallce3ff2b2009-08-25 22:02:44 +00001080Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001081 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001082 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001083 return Instantiator.Visit(D);
1084}
1085
John McCalle29ba202009-08-20 01:44:21 +00001086/// \brief Instantiates a nested template parameter list in the current
1087/// instantiation context.
1088///
1089/// \param L The parameter list to instantiate
1090///
1091/// \returns NULL if there was an error
1092TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001093TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001094 // Get errors for all the parameters before bailing out.
1095 bool Invalid = false;
1096
1097 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001098 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001099 ParamVector Params;
1100 Params.reserve(N);
1101 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1102 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001103 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001104 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001105 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001106 }
1107
1108 // Clean up if we had an error.
1109 if (Invalid) {
1110 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1111 PI != PE; ++PI)
1112 if (*PI)
1113 (*PI)->Destroy(SemaRef.Context);
1114 return NULL;
1115 }
1116
1117 TemplateParameterList *InstL
1118 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1119 L->getLAngleLoc(), &Params.front(), N,
1120 L->getRAngleLoc());
1121 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001122}
John McCalle29ba202009-08-20 01:44:21 +00001123
Douglas Gregored9c0f92009-10-29 00:04:11 +00001124/// \brief Instantiate the declaration of a class template partial
1125/// specialization.
1126///
1127/// \param ClassTemplate the (instantiated) class template that is partially
1128// specialized by the instantiation of \p PartialSpec.
1129///
1130/// \param PartialSpec the (uninstantiated) class template partial
1131/// specialization that we are instantiating.
1132///
1133/// \returns true if there was an error, false otherwise.
1134bool
1135TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1136 ClassTemplateDecl *ClassTemplate,
1137 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001138 // Create a local instantiation scope for this class template partial
1139 // specialization, which will contain the instantiations of the template
1140 // parameters.
1141 Sema::LocalInstantiationScope Scope(SemaRef);
1142
Douglas Gregored9c0f92009-10-29 00:04:11 +00001143 // Substitute into the template parameters of the class template partial
1144 // specialization.
1145 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1146 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1147 if (!InstParams)
1148 return true;
1149
1150 // Substitute into the template arguments of the class template partial
1151 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001152 const TemplateArgumentLoc *PartialSpecTemplateArgs
1153 = PartialSpec->getTemplateArgsAsWritten();
1154 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1155
1156 llvm::SmallVector<TemplateArgumentLoc, 4> InstTemplateArgs(N);
1157 for (unsigned I = 0; I != N; ++I) {
1158 if (SemaRef.Subst(PartialSpecTemplateArgs[I], InstTemplateArgs[I],
1159 TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001160 return true;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001161 }
1162
1163
1164 // Check that the template argument list is well-formed for this
1165 // class template.
1166 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1167 InstTemplateArgs.size());
1168 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1169 PartialSpec->getLocation(),
1170 /*FIXME:*/PartialSpec->getLocation(),
1171 InstTemplateArgs.data(),
1172 InstTemplateArgs.size(),
1173 /*FIXME:*/PartialSpec->getLocation(),
1174 false,
1175 Converted))
1176 return true;
1177
1178 // Figure out where to insert this class template partial specialization
1179 // in the member template's set of class template partial specializations.
1180 llvm::FoldingSetNodeID ID;
1181 ClassTemplatePartialSpecializationDecl::Profile(ID,
1182 Converted.getFlatArguments(),
1183 Converted.flatSize(),
1184 SemaRef.Context);
1185 void *InsertPos = 0;
1186 ClassTemplateSpecializationDecl *PrevDecl
1187 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1188 InsertPos);
1189
1190 // Build the canonical type that describes the converted template
1191 // arguments of the class template partial specialization.
1192 QualType CanonType
1193 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1194 Converted.getFlatArguments(),
1195 Converted.flatSize());
1196
1197 // Build the fully-sugared type for this class template
1198 // specialization as the user wrote in the specialization
1199 // itself. This means that we'll pretty-print the type retrieved
1200 // from the specialization's declaration the way that the user
1201 // actually wrote the specialization, rather than formatting the
1202 // name based on the "canonical" representation used to store the
1203 // template arguments in the specialization.
1204 QualType WrittenTy
1205 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1206 InstTemplateArgs.data(),
1207 InstTemplateArgs.size(),
1208 CanonType);
1209
1210 if (PrevDecl) {
1211 // We've already seen a partial specialization with the same template
1212 // parameters and template arguments. This can happen, for example, when
1213 // substituting the outer template arguments ends up causing two
1214 // class template partial specializations of a member class template
1215 // to have identical forms, e.g.,
1216 //
1217 // template<typename T, typename U>
1218 // struct Outer {
1219 // template<typename X, typename Y> struct Inner;
1220 // template<typename Y> struct Inner<T, Y>;
1221 // template<typename Y> struct Inner<U, Y>;
1222 // };
1223 //
1224 // Outer<int, int> outer; // error: the partial specializations of Inner
1225 // // have the same signature.
1226 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1227 << WrittenTy;
1228 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1229 << SemaRef.Context.getTypeDeclType(PrevDecl);
1230 return true;
1231 }
1232
1233
1234 // Create the class template partial specialization declaration.
1235 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1236 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1237 PartialSpec->getLocation(),
1238 InstParams,
1239 ClassTemplate,
1240 Converted,
John McCall833ca992009-10-29 08:12:44 +00001241 InstTemplateArgs.data(),
1242 InstTemplateArgs.size(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00001243 0);
1244 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1245 InstPartialSpec->setTypeAsWritten(WrittenTy);
1246
1247 // Add this partial specialization to the set of class template partial
1248 // specializations.
1249 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1250 InsertPos);
1251 return false;
1252}
1253
John McCallce3ff2b2009-08-25 22:02:44 +00001254/// \brief Does substitution on the type of the given function, including
1255/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001256///
John McCallce3ff2b2009-08-25 22:02:44 +00001257/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001258///
1259/// \param Params the instantiated parameter declarations
1260
John McCallce3ff2b2009-08-25 22:02:44 +00001261/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001262/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001263QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001264TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001265 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1266 bool InvalidDecl = false;
1267
John McCallce3ff2b2009-08-25 22:02:44 +00001268 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001269 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001270 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001271 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001272 PEnd = D->param_end();
1273 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001274 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001275 if (PInst->getType()->isVoidType()) {
1276 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1277 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001278 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001279 PInst->getType(),
1280 diag::err_abstract_type_in_decl,
1281 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001282 PInst->setInvalidDecl();
1283
1284 Params.push_back(PInst);
1285 ParamTys.push_back(PInst->getType());
1286
1287 if (PInst->isInvalidDecl())
1288 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001289 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001290 InvalidDecl = true;
1291 }
1292
1293 // FIXME: Deallocate dead declarations.
1294 if (InvalidDecl)
1295 return QualType();
1296
John McCall183700f2009-09-21 23:43:11 +00001297 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001298 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001299 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001300 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1301 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001302 if (ResultType.isNull())
1303 return QualType();
1304
Jay Foadbeaaccd2009-05-21 09:52:38 +00001305 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001306 Proto->isVariadic(), Proto->getTypeQuals(),
1307 D->getLocation(), D->getDeclName());
1308}
1309
Mike Stump1eb44332009-09-09 15:08:12 +00001310/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001311/// declaration (New) from the corresponding fields of its template (Tmpl).
1312///
1313/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001314bool
1315TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001316 FunctionDecl *Tmpl) {
1317 if (Tmpl->isDeleted())
1318 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Douglas Gregorcca9e962009-07-01 22:01:06 +00001320 // If we are performing substituting explicitly-specified template arguments
1321 // or deduced template arguments into a function template and we reach this
1322 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001323 // to keeping the new function template specialization. We therefore
1324 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001325 // into a template instantiation for this specific function template
1326 // specialization, which is not a SFINAE context, so that we diagnose any
1327 // further errors in the declaration itself.
1328 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1329 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1330 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1331 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001332 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001333 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001334 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001335 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001336 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001337 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1338 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001339 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001340 }
1341 }
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Douglas Gregore53060f2009-06-25 22:08:12 +00001343 return false;
1344}
1345
Douglas Gregor5545e162009-03-24 00:38:23 +00001346/// \brief Initializes common fields of an instantiated method
1347/// declaration (New) from the corresponding fields of its template
1348/// (Tmpl).
1349///
1350/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001351bool
1352TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001353 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001354 if (InitFunctionInstantiation(New, Tmpl))
1355 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Douglas Gregor5545e162009-03-24 00:38:23 +00001357 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1358 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +00001359 if (Tmpl->isVirtualAsWritten()) {
1360 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00001361 Record->setAggregate(false);
1362 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +00001363 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +00001364 Record->setPolymorphic(true);
1365 }
Douglas Gregor5545e162009-03-24 00:38:23 +00001366 if (Tmpl->isPure()) {
1367 New->setPure();
1368 Record->setAbstract(true);
1369 }
1370
1371 // FIXME: attributes
1372 // FIXME: New needs a pointer to Tmpl
1373 return false;
1374}
Douglas Gregora58861f2009-05-13 20:28:22 +00001375
1376/// \brief Instantiate the definition of the given function from its
1377/// template.
1378///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001379/// \param PointOfInstantiation the point at which the instantiation was
1380/// required. Note that this is not precisely a "point of instantiation"
1381/// for the function, but it's close.
1382///
Douglas Gregora58861f2009-05-13 20:28:22 +00001383/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001384/// function template specialization or member function of a class template
1385/// specialization.
1386///
1387/// \param Recursive if true, recursively instantiates any functions that
1388/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001389///
1390/// \param DefinitionRequired if true, then we are performing an explicit
1391/// instantiation where the body of the function is required. Complain if
1392/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001393void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001394 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001395 bool Recursive,
1396 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001397 if (Function->isInvalidDecl())
1398 return;
1399
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001400 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001402 // Never instantiate an explicit specialization.
1403 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1404 return;
1405
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001406 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001407 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001408 Stmt *Pattern = 0;
1409 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001410 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001411
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001412 if (!Pattern) {
1413 if (DefinitionRequired) {
1414 if (Function->getPrimaryTemplate())
1415 Diag(PointOfInstantiation,
1416 diag::err_explicit_instantiation_undefined_func_template)
1417 << Function->getPrimaryTemplate();
1418 else
1419 Diag(PointOfInstantiation,
1420 diag::err_explicit_instantiation_undefined_member)
1421 << 1 << Function->getDeclName() << Function->getDeclContext();
1422
1423 if (PatternDecl)
1424 Diag(PatternDecl->getLocation(),
1425 diag::note_explicit_instantiation_here);
1426 }
1427
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001428 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001429 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001430
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001431 // C++0x [temp.explicit]p9:
1432 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001433 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001434 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001435 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001436 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001437 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001438 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001440 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1441 if (Inst)
1442 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001443
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001444 // If we're performing recursive template instantiation, create our own
1445 // queue of pending implicit instantiations that we will instantiate later,
1446 // while we're still within our own instantiation context.
1447 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1448 if (Recursive)
1449 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001451 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1452
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001453 // Introduce a new scope where local variable instantiations will be
1454 // recorded.
1455 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001457 // Introduce the instantiated function parameters into the local
1458 // instantiation scope.
1459 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1460 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1461 Function->getParamDecl(I));
1462
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001463 // Enter the scope of this instantiation. We don't use
1464 // PushDeclContext because we don't have a scope.
1465 DeclContext *PreviousContext = CurContext;
1466 CurContext = Function;
1467
Mike Stump1eb44332009-09-09 15:08:12 +00001468 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001469 getTemplateInstantiationArgs(Function);
1470
1471 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001472 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001473 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1474 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1475 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001476 }
1477
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001478 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001479 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001480
Douglas Gregor52604ab2009-09-11 21:19:12 +00001481 if (Body.isInvalid())
1482 Function->setInvalidDecl();
1483
Mike Stump1eb44332009-09-09 15:08:12 +00001484 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001485 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001486
1487 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001488
1489 DeclGroupRef DG(Function);
1490 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001492 if (Recursive) {
1493 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001494 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001495 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001497 // Restore the set of pending implicit instantiations.
1498 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1499 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001500}
1501
1502/// \brief Instantiate the definition of the given variable from its
1503/// template.
1504///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001505/// \param PointOfInstantiation the point at which the instantiation was
1506/// required. Note that this is not precisely a "point of instantiation"
1507/// for the function, but it's close.
1508///
1509/// \param Var the already-instantiated declaration of a static member
1510/// variable of a class template specialization.
1511///
1512/// \param Recursive if true, recursively instantiates any functions that
1513/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001514///
1515/// \param DefinitionRequired if true, then we are performing an explicit
1516/// instantiation where an out-of-line definition of the member variable
1517/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001518void Sema::InstantiateStaticDataMemberDefinition(
1519 SourceLocation PointOfInstantiation,
1520 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001521 bool Recursive,
1522 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001523 if (Var->isInvalidDecl())
1524 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Douglas Gregor7caa6822009-07-24 20:34:43 +00001526 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001527 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001528 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001529 assert(Def->isStaticDataMember() && "Not a static data member?");
1530 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Douglas Gregor0d035142009-10-27 18:42:08 +00001532 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001533 // We did not find an out-of-line definition of this static data member,
1534 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001535 // instantiate this definition (or provide a specialization for it) in
1536 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001537 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001538 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001539 Diag(PointOfInstantiation,
1540 diag::err_explicit_instantiation_undefined_member)
1541 << 2 << Var->getDeclName() << Var->getDeclContext();
1542 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1543 }
1544
Douglas Gregor7caa6822009-07-24 20:34:43 +00001545 return;
1546 }
1547
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001548 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001549 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001550 return;
1551
1552 // C++0x [temp.explicit]p9:
1553 // Except for inline functions, other explicit instantiation declarations
1554 // have the effect of suppressing the implicit instantiation of the entity
1555 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001556 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001557 == TSK_ExplicitInstantiationDeclaration)
1558 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Douglas Gregor7caa6822009-07-24 20:34:43 +00001560 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1561 if (Inst)
1562 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Douglas Gregor7caa6822009-07-24 20:34:43 +00001564 // If we're performing recursive template instantiation, create our own
1565 // queue of pending implicit instantiations that we will instantiate later,
1566 // while we're still within our own instantiation context.
1567 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1568 if (Recursive)
1569 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Douglas Gregor7caa6822009-07-24 20:34:43 +00001571 // Enter the scope of this instantiation. We don't use
1572 // PushDeclContext because we don't have a scope.
1573 DeclContext *PreviousContext = CurContext;
1574 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001576 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001577 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001578 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001579 CurContext = PreviousContext;
1580
1581 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001582 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001583 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1584 assert(MSInfo && "Missing member specialization information?");
1585 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1586 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001587 DeclGroupRef DG(Var);
1588 Consumer.HandleTopLevelDecl(DG);
1589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregor7caa6822009-07-24 20:34:43 +00001591 if (Recursive) {
1592 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001593 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001594 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Douglas Gregor7caa6822009-07-24 20:34:43 +00001596 // Restore the set of pending implicit instantiations.
1597 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001598 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001599}
Douglas Gregor815215d2009-05-27 05:35:12 +00001600
Anders Carlsson09025312009-08-29 05:16:22 +00001601void
1602Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1603 const CXXConstructorDecl *Tmpl,
1604 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Anders Carlsson09025312009-08-29 05:16:22 +00001606 llvm::SmallVector<MemInitTy*, 4> NewInits;
1607
1608 // Instantiate all the initializers.
1609 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001610 InitsEnd = Tmpl->init_end();
1611 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001612 CXXBaseOrMemberInitializer *Init = *Inits;
1613
1614 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Anders Carlsson09025312009-08-29 05:16:22 +00001616 // Instantiate all the arguments.
1617 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1618 Args != ArgsEnd; ++Args) {
1619 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1620
1621 if (NewArg.isInvalid())
1622 New->setInvalidDecl();
1623 else
1624 NewArgs.push_back(NewArg.takeAs<Expr>());
1625 }
1626
1627 MemInitResult NewInit;
1628
1629 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001630 QualType BaseType(Init->getBaseClass(), 0);
1631 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1632 New->getDeclName());
Anders Carlsson09025312009-08-29 05:16:22 +00001633
1634 NewInit = BuildBaseInitializer(BaseType,
Mike Stump1eb44332009-09-09 15:08:12 +00001635 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001636 NewArgs.size(),
1637 Init->getSourceLocation(),
1638 Init->getRParenLoc(),
1639 New->getParent());
1640 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001641 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001643 // Is this an anonymous union?
1644 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001645 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001646 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001647 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1648 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001649
1650 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001651 NewArgs.size(),
1652 Init->getSourceLocation(),
1653 Init->getRParenLoc());
1654 }
1655
1656 if (NewInit.isInvalid())
1657 New->setInvalidDecl();
1658 else {
1659 // FIXME: It would be nice if ASTOwningVector had a release function.
1660 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Anders Carlsson09025312009-08-29 05:16:22 +00001662 NewInits.push_back((MemInitTy *)NewInit.get());
1663 }
1664 }
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Anders Carlsson09025312009-08-29 05:16:22 +00001666 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001667 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001668 /*FIXME: ColonLoc */
1669 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001670 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001671}
1672
John McCall52a575a2009-08-29 08:11:13 +00001673// TODO: this could be templated if the various decl types used the
1674// same method name.
1675static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1676 ClassTemplateDecl *Instance) {
1677 Pattern = Pattern->getCanonicalDecl();
1678
1679 do {
1680 Instance = Instance->getCanonicalDecl();
1681 if (Pattern == Instance) return true;
1682 Instance = Instance->getInstantiatedFromMemberTemplate();
1683 } while (Instance);
1684
1685 return false;
1686}
1687
Douglas Gregor0d696532009-09-28 06:34:35 +00001688static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1689 FunctionTemplateDecl *Instance) {
1690 Pattern = Pattern->getCanonicalDecl();
1691
1692 do {
1693 Instance = Instance->getCanonicalDecl();
1694 if (Pattern == Instance) return true;
1695 Instance = Instance->getInstantiatedFromMemberTemplate();
1696 } while (Instance);
1697
1698 return false;
1699}
1700
Douglas Gregored9c0f92009-10-29 00:04:11 +00001701static bool
1702isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1703 ClassTemplatePartialSpecializationDecl *Instance) {
1704 Pattern
1705 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1706 do {
1707 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1708 Instance->getCanonicalDecl());
1709 if (Pattern == Instance)
1710 return true;
1711 Instance = Instance->getInstantiatedFromMember();
1712 } while (Instance);
1713
1714 return false;
1715}
1716
John McCall52a575a2009-08-29 08:11:13 +00001717static bool isInstantiationOf(CXXRecordDecl *Pattern,
1718 CXXRecordDecl *Instance) {
1719 Pattern = Pattern->getCanonicalDecl();
1720
1721 do {
1722 Instance = Instance->getCanonicalDecl();
1723 if (Pattern == Instance) return true;
1724 Instance = Instance->getInstantiatedFromMemberClass();
1725 } while (Instance);
1726
1727 return false;
1728}
1729
1730static bool isInstantiationOf(FunctionDecl *Pattern,
1731 FunctionDecl *Instance) {
1732 Pattern = Pattern->getCanonicalDecl();
1733
1734 do {
1735 Instance = Instance->getCanonicalDecl();
1736 if (Pattern == Instance) return true;
1737 Instance = Instance->getInstantiatedFromMemberFunction();
1738 } while (Instance);
1739
1740 return false;
1741}
1742
1743static bool isInstantiationOf(EnumDecl *Pattern,
1744 EnumDecl *Instance) {
1745 Pattern = Pattern->getCanonicalDecl();
1746
1747 do {
1748 Instance = Instance->getCanonicalDecl();
1749 if (Pattern == Instance) return true;
1750 Instance = Instance->getInstantiatedFromMemberEnum();
1751 } while (Instance);
1752
1753 return false;
1754}
1755
John McCall7ba107a2009-11-18 02:36:19 +00001756static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1757 UsingDecl *Instance,
1758 ASTContext &C) {
1759 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1760}
1761
1762static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001763 UsingDecl *Instance,
1764 ASTContext &C) {
1765 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1766}
1767
John McCall52a575a2009-08-29 08:11:13 +00001768static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1769 VarDecl *Instance) {
1770 assert(Instance->isStaticDataMember());
1771
1772 Pattern = Pattern->getCanonicalDecl();
1773
1774 do {
1775 Instance = Instance->getCanonicalDecl();
1776 if (Pattern == Instance) return true;
1777 Instance = Instance->getInstantiatedFromStaticDataMember();
1778 } while (Instance);
1779
1780 return false;
1781}
1782
Douglas Gregor815215d2009-05-27 05:35:12 +00001783static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001784 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001785 if (UnresolvedUsingTypenameDecl *UUD
1786 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1787 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1788 return isInstantiationOf(UUD, UD, Ctx);
1789 }
1790 }
1791
1792 if (UnresolvedUsingValueDecl *UUD
1793 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001794 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1795 return isInstantiationOf(UUD, UD, Ctx);
1796 }
1797 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001798
Anders Carlsson0d8df782009-08-29 19:37:28 +00001799 return false;
1800 }
Mike Stump1eb44332009-09-09 15:08:12 +00001801
John McCall52a575a2009-08-29 08:11:13 +00001802 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1803 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001804
John McCall52a575a2009-08-29 08:11:13 +00001805 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1806 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001807
John McCall52a575a2009-08-29 08:11:13 +00001808 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1809 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001810
Douglas Gregor7caa6822009-07-24 20:34:43 +00001811 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001812 if (Var->isStaticDataMember())
1813 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1814
1815 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1816 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001817
Douglas Gregor0d696532009-09-28 06:34:35 +00001818 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1819 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1820
Douglas Gregored9c0f92009-10-29 00:04:11 +00001821 if (ClassTemplatePartialSpecializationDecl *PartialSpec
1822 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
1823 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
1824 PartialSpec);
1825
Anders Carlssond8b285f2009-09-01 04:26:58 +00001826 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1827 if (!Field->getDeclName()) {
1828 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00001829 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00001830 cast<FieldDecl>(D);
1831 }
1832 }
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Douglas Gregor815215d2009-05-27 05:35:12 +00001834 return D->getDeclName() && isa<NamedDecl>(Other) &&
1835 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1836}
1837
1838template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00001839static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00001840 NamedDecl *D,
1841 ForwardIterator first,
1842 ForwardIterator last) {
1843 for (; first != last; ++first)
1844 if (isInstantiationOf(Ctx, D, *first))
1845 return cast<NamedDecl>(*first);
1846
1847 return 0;
1848}
1849
John McCall02cace72009-08-28 07:59:38 +00001850/// \brief Finds the instantiation of the given declaration context
1851/// within the current instantiation.
1852///
1853/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00001854DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1855 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00001856 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00001857 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00001858 return cast_or_null<DeclContext>(ID);
1859 } else return DC;
1860}
1861
Douglas Gregored961e72009-05-27 17:54:46 +00001862/// \brief Find the instantiation of the given declaration within the
1863/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001864///
1865/// This routine is intended to be used when \p D is a declaration
1866/// referenced from within a template, that needs to mapped into the
1867/// corresponding declaration within an instantiation. For example,
1868/// given:
1869///
1870/// \code
1871/// template<typename T>
1872/// struct X {
1873/// enum Kind {
1874/// KnownValue = sizeof(T)
1875/// };
1876///
1877/// bool getKind() const { return KnownValue; }
1878/// };
1879///
1880/// template struct X<int>;
1881/// \endcode
1882///
1883/// In the instantiation of X<int>::getKind(), we need to map the
1884/// EnumConstantDecl for KnownValue (which refers to
1885/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001886/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1887/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00001888NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1889 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor44c73842009-09-01 17:53:10 +00001890 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1891 // Transform all of the elements of the overloaded function set.
Mike Stump1eb44332009-09-09 15:08:12 +00001892 OverloadedFunctionDecl *Result
Douglas Gregor44c73842009-09-01 17:53:10 +00001893 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregor44c73842009-09-01 17:53:10 +00001895 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1896 FEnd = Ovl->function_end();
1897 F != FEnd; ++F) {
1898 Result->addOverload(
Douglas Gregore95b4092009-09-16 18:34:49 +00001899 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F,
1900 TemplateArgs)));
Douglas Gregor44c73842009-09-01 17:53:10 +00001901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregor44c73842009-09-01 17:53:10 +00001903 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001904 }
1905
Douglas Gregor815215d2009-05-27 05:35:12 +00001906 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00001907 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
1908 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
1909 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001910 // D is a local of some kind. Look into the map of local
1911 // declarations to their instantiations.
1912 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1913 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001914
Douglas Gregore95b4092009-09-16 18:34:49 +00001915 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1916 if (!Record->isDependentContext())
1917 return D;
1918
1919 // If the RecordDecl is actually the injected-class-name or a "templated"
1920 // declaration for a class template or class template partial
1921 // specialization, substitute into the injected-class-name of the
1922 // class template or partial specialization to find the new DeclContext.
1923 QualType T;
1924 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1925
1926 if (ClassTemplate) {
1927 T = ClassTemplate->getInjectedClassNameType(Context);
1928 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1929 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1930 T = Context.getTypeDeclType(Record);
1931 ClassTemplate = PartialSpec->getSpecializedTemplate();
1932 }
1933
1934 if (!T.isNull()) {
1935 // Substitute into the injected-class-name to get the type corresponding
1936 // to the instantiation we want. This substitution should never fail,
1937 // since we know we can instantiate the injected-class-name or we wouldn't
1938 // have gotten to the injected-class-name!
1939 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1940 // instantiation in the common case?
1941 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1942 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1943
1944 if (!T->isDependentType()) {
1945 assert(T->isRecordType() && "Instantiation must produce a record type");
1946 return T->getAs<RecordType>()->getDecl();
1947 }
1948
1949 // We are performing "partial" template instantiation to create the
1950 // member declarations for the members of a class template
1951 // specialization. Therefore, D is actually referring to something in
1952 // the current instantiation. Look through the current context,
1953 // which contains actual instantiations, to find the instantiation of
1954 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00001955 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00001956 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001957 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00001958 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00001959 if (isInstantiationOf(ClassTemplate,
1960 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00001961 return Spec;
1962 }
1963
Mike Stump1eb44332009-09-09 15:08:12 +00001964 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00001965 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00001966 return Record;
John McCall52a575a2009-08-29 08:11:13 +00001967 }
Douglas Gregore95b4092009-09-16 18:34:49 +00001968
1969 // Fall through to deal with other dependent record types (e.g.,
1970 // anonymous unions in class templates).
1971 }
John McCall52a575a2009-08-29 08:11:13 +00001972
Douglas Gregore95b4092009-09-16 18:34:49 +00001973 if (!ParentDC->isDependentContext())
1974 return D;
1975
1976 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001977 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00001978 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregor815215d2009-05-27 05:35:12 +00001980 if (ParentDC != D->getDeclContext()) {
1981 // We performed some kind of instantiation in the parent context,
1982 // so now we need to look into the instantiated parent context to
1983 // find the instantiation of the declaration D.
1984 NamedDecl *Result = 0;
1985 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001986 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001987 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1988 } else {
1989 // Since we don't have a name for the entity we're looking for,
1990 // our only option is to walk through all of the declarations to
1991 // find that name. This will occur in a few cases:
1992 //
1993 // - anonymous struct/union within a template
1994 // - unnamed class/struct/union/enum within a template
1995 //
1996 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00001997 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001998 ParentDC->decls_begin(),
1999 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002000 }
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Douglas Gregor815215d2009-05-27 05:35:12 +00002002 assert(Result && "Unable to find instantiation of declaration!");
2003 D = Result;
2004 }
2005
Douglas Gregor815215d2009-05-27 05:35:12 +00002006 return D;
2007}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002008
Mike Stump1eb44332009-09-09 15:08:12 +00002009/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002010/// instantiations we have seen until this point.
2011void Sema::PerformPendingImplicitInstantiations() {
2012 while (!PendingImplicitInstantiations.empty()) {
2013 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002014 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Douglas Gregor7caa6822009-07-24 20:34:43 +00002016 // Instantiate function definitions
2017 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002018 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002019 Function->getLocation(), *this,
2020 Context.getSourceManager(),
2021 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002023 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002024 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002025 continue;
2026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregor7caa6822009-07-24 20:34:43 +00002028 // Instantiate static data member definitions.
2029 VarDecl *Var = cast<VarDecl>(Inst.first);
2030 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002031
Mike Stump1eb44332009-09-09 15:08:12 +00002032 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002033 Var->getLocation(), *this,
2034 Context.getSourceManager(),
2035 "instantiating static data member "
2036 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Douglas Gregor7caa6822009-07-24 20:34:43 +00002038 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002039 }
2040}