blob: ec28f474179939dc00200c0f6f1de8a1a9af051e [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000019#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021
22using namespace clang;
23
24namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000025 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000026 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000027 Sema &SemaRef;
28 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000029 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Anders Carlssond8fe2d52009-11-07 06:07:58 +000031 void InstantiateAttrs(Decl *Tmpl, Decl *New);
32
Douglas Gregor8dbc2692009-03-17 21:15:40 +000033 public:
34 typedef Sema::OwningExprResult OwningExprResult;
35
36 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000037 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000038 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000039
Mike Stump390b4cc2009-05-16 07:39:55 +000040 // FIXME: Once we get closer to completion, replace these manually-written
41 // declarations with automatically-generated ones from
42 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000043 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
44 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000045 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000046 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitFieldDecl(FieldDecl *D);
48 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
49 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000050 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000051 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000052 Decl *VisitFunctionDecl(FunctionDecl *D,
53 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000054 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000055 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
56 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000057 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000058 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000059 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000060 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000061 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000062 Decl *VisitClassTemplatePartialSpecializationDecl(
63 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000064 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000066 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000067 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000068 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000069 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
70 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000071
Douglas Gregor8dbc2692009-03-17 21:15:40 +000072 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000073 Decl *VisitDecl(Decl *D) {
74 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
75 Diagnostic::Error,
76 "cannot instantiate %0 yet");
77 SemaRef.Diag(D->getLocation(), DiagID)
78 << D->getDeclKindName();
79
Douglas Gregor8dbc2692009-03-17 21:15:40 +000080 return 0;
81 }
Douglas Gregor5545e162009-03-24 00:38:23 +000082
John McCallfd810b12009-08-14 02:03:10 +000083 const LangOptions &getLangOptions() {
84 return SemaRef.getLangOptions();
85 }
86
Douglas Gregor5545e162009-03-24 00:38:23 +000087 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000088 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000089 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000090 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000091 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000092
93 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000094 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000095
96 bool InstantiateClassTemplatePartialSpecialization(
97 ClassTemplateDecl *ClassTemplate,
98 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000099 };
100}
101
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000102// FIXME: Is this too simple?
103void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
104 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
105 TmplAttr = TmplAttr->getNext()) {
106
107 // FIXME: Is cloning correct for all attributes?
108 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
109
110 New->addAttr(NewAttr);
111 }
112}
113
Douglas Gregor4f722be2009-03-25 15:45:12 +0000114Decl *
115TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
116 assert(false && "Translation units cannot be instantiated");
117 return D;
118}
119
120Decl *
121TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
122 assert(false && "Namespaces cannot be instantiated");
123 return D;
124}
125
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000126Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
127 bool Invalid = false;
John McCallba6a9bd2009-10-24 08:00:42 +0000128 DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
129 if (DI->getType()->isDependentType()) {
130 DI = SemaRef.SubstType(DI, TemplateArgs,
131 D->getLocation(), D->getDeclName());
132 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000133 Invalid = true;
John McCallba6a9bd2009-10-24 08:00:42 +0000134 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000135 }
136 }
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 // Create the new typedef
139 TypedefDecl *Typedef
140 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000141 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142 if (Invalid)
143 Typedef->setInvalidDecl();
144
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000145 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 return Typedef;
148}
149
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000150Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000151 // Do substitution on the type of the declaration
John McCall0a5fa062009-10-21 02:39:02 +0000152 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(),
153 TemplateArgs,
154 D->getTypeSpecStartLoc(),
155 D->getDeclName());
156 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000157 return 0;
158
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000159 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000160 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
161 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000162 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000163 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000164 Var->setThreadSpecified(D->isThreadSpecified());
165 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
166 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000167
168 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000169 // out-of-line, the instantiation will have the same lexical
170 // context (which will be a namespace scope) as the template.
171 if (D->isOutOfLine())
172 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Mike Stump390b4cc2009-05-16 07:39:55 +0000174 // FIXME: In theory, we could have a previous declaration for variables that
175 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000176 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000177 // FIXME: having to fake up a LookupResult is dumb.
178 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
179 Sema::LookupOrdinaryName);
180 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Douglas Gregor7caa6822009-07-24 20:34:43 +0000182 if (D->isOutOfLine()) {
183 D->getLexicalDeclContext()->addDecl(Var);
184 Owner->makeDeclVisibleInContext(Var);
185 } else {
186 Owner->addDecl(Var);
187 }
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000189 // Link instantiations of static data members back to the template from
190 // which they were instantiated.
191 if (Var->isStaticDataMember())
192 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000193 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000194
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000195 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000196 if (Var->isStaticDataMember() && !D->isOutOfLine())
197 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
198 else
199 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
200
Mike Stump1eb44332009-09-09 15:08:12 +0000201 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000202 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000203 if (Init.isInvalid())
204 Var->setInvalidDecl();
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000205 else if (!D->getType()->isDependentType() &&
206 !D->getInit()->isTypeDependent() &&
Douglas Gregore48319a2009-11-09 17:16:50 +0000207 !D->getInit()->isValueDependent()) {
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000208 // If neither the declaration's type nor its initializer are dependent,
209 // we don't want to redo all the checking, especially since the
210 // initializer might have been wrapped by a CXXConstructExpr since we did
211 // it the first time.
Anders Carlssona244dc32009-11-24 16:52:50 +0000212 Var->setType(D->getType());
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000213 Var->setInit(SemaRef.Context, Init.takeAs<Expr>());
214 }
Douglas Gregor83ddad32009-08-26 21:14:46 +0000215 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000216 // FIXME: We're faking all of the comma locations, which is suboptimal.
Douglas Gregor83ddad32009-08-26 21:14:46 +0000217 // Do we even need these comma locations?
218 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
219 if (PLE->getNumExprs() > 0) {
220 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
221 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
222 Expr *E = PLE->getExpr(I)->Retain();
223 FakeCommaLocs.push_back(
224 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
225 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000226 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Douglas Gregor83ddad32009-08-26 21:14:46 +0000229 // Add the direct initializer to the declaration.
230 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Mike Stump1eb44332009-09-09 15:08:12 +0000231 PLE->getLParenLoc(),
Douglas Gregor83ddad32009-08-26 21:14:46 +0000232 Sema::MultiExprArg(SemaRef,
233 (void**)PLE->getExprs(),
234 PLE->getNumExprs()),
235 FakeCommaLocs.data(),
236 PLE->getRParenLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Douglas Gregor83ddad32009-08-26 21:14:46 +0000238 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
239 // we've explicitly retained all of its subexpressions already.
240 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000241 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000242 D->hasCXXDirectInitializer());
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000243 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000244 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
245 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000246
247 return Var;
248}
249
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000250Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
251 bool Invalid = false;
John McCall07fb6be2009-10-22 23:33:21 +0000252 DeclaratorInfo *DI = D->getDeclaratorInfo();
253 if (DI->getType()->isDependentType()) {
254 DI = SemaRef.SubstType(DI, TemplateArgs,
255 D->getLocation(), D->getDeclName());
256 if (!DI) {
257 DI = D->getDeclaratorInfo();
258 Invalid = true;
259 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000260 // C++ [temp.arg.type]p3:
261 // If a declaration acquires a function type through a type
262 // dependent on a template-parameter and this causes a
263 // declaration that does not use the syntactic form of a
264 // function declarator to have function type, the program is
265 // ill-formed.
266 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000267 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000268 Invalid = true;
269 }
270 }
271
272 Expr *BitWidth = D->getBitWidth();
273 if (Invalid)
274 BitWidth = 0;
275 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000276 // The bit-width expression is not potentially evaluated.
277 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000279 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000280 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000281 if (InstantiatedBitWidth.isInvalid()) {
282 Invalid = true;
283 BitWidth = 0;
284 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000285 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000286 }
287
John McCall07fb6be2009-10-22 23:33:21 +0000288 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
289 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000290 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000291 D->getLocation(),
292 D->isMutable(),
293 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000294 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000295 D->getAccess(),
296 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000297 if (!Field) {
298 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000299 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000300 }
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000302 InstantiateAttrs(D, Field);
303
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000304 if (Invalid)
305 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000307 if (!Field->getDeclName()) {
308 // Keep track of where this decl came from.
309 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000310 }
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000312 Field->setImplicit(D->isImplicit());
313 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000314
315 return Field;
316}
317
John McCall02cace72009-08-28 07:59:38 +0000318Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
319 FriendDecl::FriendUnion FU;
320
321 // Handle friend type expressions by simply substituting template
322 // parameters into the pattern type.
323 if (Type *Ty = D->getFriendType()) {
324 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
325 D->getLocation(), DeclarationName());
326 if (T.isNull()) return 0;
327
328 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
329 FU = T.getTypePtr();
330
331 // Handle everything else by appropriate substitution.
332 } else {
333 NamedDecl *ND = D->getFriendDecl();
334 assert(ND && "friend decl must be a decl or a type!");
335
Douglas Gregora735b202009-10-13 14:39:41 +0000336 // FIXME: We have a problem here, because the nested call to Visit(ND)
337 // will inject the thing that the friend references into the current
338 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000339 Decl *NewND = Visit(ND);
340 if (!NewND) return 0;
341
342 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000343 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
John McCall02cace72009-08-28 07:59:38 +0000345 FriendDecl *FD =
346 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
347 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000348 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000349 Owner->addDecl(FD);
350 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000351}
352
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000353Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
354 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Douglas Gregorac7610d2009-06-22 20:57:11 +0000356 // The expression in a static assertion is not potentially evaluated.
357 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000359 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000360 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000361 if (InstantiatedAssertExpr.isInvalid())
362 return 0;
363
Douglas Gregor43d9d922009-08-08 01:41:12 +0000364 OwningExprResult Message(SemaRef, D->getMessage());
365 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000366 Decl *StaticAssert
367 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000368 move(InstantiatedAssertExpr),
369 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000370 return StaticAssert;
371}
372
373Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000374 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000375 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000376 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000377 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000378 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000379 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000380 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000381 Enum->startDefinition();
382
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000383 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000384
385 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000386 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
387 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000388 EC != ECEnd; ++EC) {
389 // The specified value for the enumerator.
390 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000391 if (Expr *UninstValue = EC->getInitExpr()) {
392 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000393 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000394 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000395
John McCallce3ff2b2009-08-25 22:02:44 +0000396 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000397 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000398
399 // Drop the initial value and continue.
400 bool isInvalid = false;
401 if (Value.isInvalid()) {
402 Value = SemaRef.Owned((Expr *)0);
403 isInvalid = true;
404 }
405
Mike Stump1eb44332009-09-09 15:08:12 +0000406 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000407 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
408 EC->getLocation(), EC->getIdentifier(),
409 move(Value));
410
411 if (isInvalid) {
412 if (EnumConst)
413 EnumConst->setInvalidDecl();
414 Enum->setInvalidDecl();
415 }
416
417 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000418 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000419 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000420 LastEnumConst = EnumConst;
421 }
422 }
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000424 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000425 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000426 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
427 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000428 &Enumerators[0], Enumerators.size(),
429 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430
431 return Enum;
432}
433
Douglas Gregor6477b692009-03-25 15:04:13 +0000434Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
435 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
436 return 0;
437}
438
Douglas Gregored9c0f92009-10-29 00:04:11 +0000439namespace {
440 class SortDeclByLocation {
441 SourceManager &SourceMgr;
442
443 public:
444 explicit SortDeclByLocation(SourceManager &SourceMgr)
445 : SourceMgr(SourceMgr) { }
446
447 bool operator()(const Decl *X, const Decl *Y) const {
448 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
449 Y->getLocation());
450 }
451 };
452}
453
John McCalle29ba202009-08-20 01:44:21 +0000454Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000455 // Create a local instantiation scope for this class template, which
456 // will contain the instantiations of the template parameters.
457 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000458 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000459 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000460 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000461 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000462
463 CXXRecordDecl *Pattern = D->getTemplatedDecl();
464 CXXRecordDecl *RecordInst
465 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
466 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000467 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
468 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000469
470 ClassTemplateDecl *Inst
471 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
472 D->getIdentifier(), InstParams, RecordInst, 0);
473 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000474 if (D->getFriendObjectKind())
475 Inst->setObjectOfFriendDecl(true);
476 else
477 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000478 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000479
480 // Trigger creation of the type for the instantiation.
481 SemaRef.Context.getTypeDeclType(RecordInst);
482
Douglas Gregor259571e2009-10-30 22:42:42 +0000483 // Finish handling of friends.
484 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000485 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000486 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000487
John McCalle29ba202009-08-20 01:44:21 +0000488 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000489
490 // First, we sort the partial specializations by location, so
491 // that we instantiate them in the order they were declared.
492 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
493 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
494 P = D->getPartialSpecializations().begin(),
495 PEnd = D->getPartialSpecializations().end();
496 P != PEnd; ++P)
497 PartialSpecs.push_back(&*P);
498 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
499 SortDeclByLocation(SemaRef.SourceMgr));
500
501 // Instantiate all of the partial specializations of this member class
502 // template.
503 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
504 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
505
John McCalle29ba202009-08-20 01:44:21 +0000506 return Inst;
507}
508
Douglas Gregord60e1052009-08-27 16:57:43 +0000509Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000510TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
511 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000512 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
513
514 // Lookup the already-instantiated declaration in the instantiation
515 // of the class template and return that.
516 DeclContext::lookup_result Found
517 = Owner->lookup(ClassTemplate->getDeclName());
518 if (Found.first == Found.second)
519 return 0;
520
521 ClassTemplateDecl *InstClassTemplate
522 = dyn_cast<ClassTemplateDecl>(*Found.first);
523 if (!InstClassTemplate)
524 return 0;
525
526 Decl *DCanon = D->getCanonicalDecl();
527 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
528 P = InstClassTemplate->getPartialSpecializations().begin(),
529 PEnd = InstClassTemplate->getPartialSpecializations().end();
530 P != PEnd; ++P) {
531 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
532 return &*P;
533 }
534
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000535 return 0;
536}
537
538Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000539TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000540 // Create a local instantiation scope for this function template, which
541 // will contain the instantiations of the template parameters and then get
542 // merged with the local instantiation scope for the function template
543 // itself.
544 Sema::LocalInstantiationScope Scope(SemaRef);
545
Douglas Gregord60e1052009-08-27 16:57:43 +0000546 TemplateParameterList *TempParams = D->getTemplateParameters();
547 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000548 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000549 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000550
Douglas Gregora735b202009-10-13 14:39:41 +0000551 FunctionDecl *Instantiated = 0;
552 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
553 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
554 InstParams));
555 else
556 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
557 D->getTemplatedDecl(),
558 InstParams));
559
560 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000561 return 0;
562
Mike Stump1eb44332009-09-09 15:08:12 +0000563 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000564 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000565 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000566 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000567 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000568 assert(InstTemplate &&
569 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
570 if (!InstTemplate->getInstantiatedFromMemberTemplate())
571 InstTemplate->setInstantiatedFromMemberTemplate(D);
572
573 // Add non-friends into the owner.
574 if (!InstTemplate->getFriendObjectKind())
575 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000576 return InstTemplate;
577}
578
Douglas Gregord475b8d2009-03-25 21:17:03 +0000579Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
580 CXXRecordDecl *PrevDecl = 0;
581 if (D->isInjectedClassName())
582 PrevDecl = cast<CXXRecordDecl>(Owner);
583
584 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000585 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000586 D->getLocation(), D->getIdentifier(),
587 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000588 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000589 // FIXME: Check against AS_none is an ugly hack to work around the issue that
590 // the tag decls introduced by friend class declarations don't have an access
591 // specifier. Remove once this area of the code gets sorted out.
592 if (D->getAccess() != AS_none)
593 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000594 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000595 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000596
John McCall02cace72009-08-28 07:59:38 +0000597 // If the original function was part of a friend declaration,
598 // inherit its namespace state.
599 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
600 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
601
Anders Carlssond8b285f2009-09-01 04:26:58 +0000602 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
603
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000604 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000605 return Record;
606}
607
John McCall02cace72009-08-28 07:59:38 +0000608/// Normal class members are of more specific types and therefore
609/// don't make it here. This function serves two purposes:
610/// 1) instantiating function templates
611/// 2) substituting friend declarations
612/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000613 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
614 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000615 // Check whether there is already a function template specialization for
616 // this declaration.
617 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
618 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000619 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000620 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000621 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000622 TemplateArgs.getInnermost().getFlatArgumentList(),
623 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000624 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
626 FunctionTemplateSpecializationInfo *Info
627 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000628 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Douglas Gregor127102b2009-06-29 20:59:39 +0000630 // If we already have a function template specialization, return it.
631 if (Info)
632 return Info->Function;
633 }
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Douglas Gregor550d9b22009-10-31 17:21:17 +0000635 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregore53060f2009-06-25 22:08:12 +0000637 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000638 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000639 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000640 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000641
Douglas Gregore53060f2009-06-25 22:08:12 +0000642 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000643 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
644 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000645 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000646 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000647 D->getDeclName(), T, D->getDeclaratorInfo(),
648 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000649 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000650 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Douglas Gregore53060f2009-06-25 22:08:12 +0000652 // Attach the parameters
653 for (unsigned P = 0; P < Params.size(); ++P)
654 Params[P]->setOwningFunction(Function);
655 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000656
Douglas Gregora735b202009-10-13 14:39:41 +0000657 if (TemplateParams) {
658 // Our resulting instantiation is actually a function template, since we
659 // are substituting only the outer template parameters. For example, given
660 //
661 // template<typename T>
662 // struct X {
663 // template<typename U> friend void f(T, U);
664 // };
665 //
666 // X<int> x;
667 //
668 // We are instantiating the friend function template "f" within X<int>,
669 // which means substituting int for T, but leaving "f" as a friend function
670 // template.
671 // Build the function template itself.
672 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
673 Function->getLocation(),
674 Function->getDeclName(),
675 TemplateParams, Function);
676 Function->setDescribedFunctionTemplate(FunctionTemplate);
677 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000678 } else if (FunctionTemplate) {
679 // Record this function template specialization.
680 Function->setFunctionTemplateSpecialization(SemaRef.Context,
681 FunctionTemplate,
682 &TemplateArgs.getInnermost(),
683 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000684 }
Douglas Gregora735b202009-10-13 14:39:41 +0000685
Douglas Gregore53060f2009-06-25 22:08:12 +0000686 if (InitFunctionInstantiation(Function, D))
687 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Douglas Gregore53060f2009-06-25 22:08:12 +0000689 bool Redeclaration = false;
690 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000691
John McCall68263142009-11-18 22:49:29 +0000692 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
693 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
694
Douglas Gregora735b202009-10-13 14:39:41 +0000695 if (TemplateParams || !FunctionTemplate) {
696 // Look only into the namespace where the friend would be declared to
697 // find a previous declaration. This is the innermost enclosing namespace,
698 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000699 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000700
Douglas Gregora735b202009-10-13 14:39:41 +0000701 // In C++, the previous declaration we find might be a tag type
702 // (class or enum). In this case, the new declaration will hide the
703 // tag type. Note that this does does not apply if we're declaring a
704 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000705 if (Previous.isSingleTagDecl())
706 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000707 }
708
John McCall68263142009-11-18 22:49:29 +0000709 SemaRef.CheckFunctionDeclaration(Function, Previous, false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000710 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000711
Douglas Gregora735b202009-10-13 14:39:41 +0000712 // If the original function was part of a friend declaration,
713 // inherit its namespace state and add it to the owner.
714 NamedDecl *FromFriendD
715 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
716 if (FromFriendD->getFriendObjectKind()) {
717 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000718 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000719 if (TemplateParams) {
720 ToFriendD = cast<NamedDecl>(FunctionTemplate);
721 PrevDecl = FunctionTemplate->getPreviousDeclaration();
722 } else {
723 ToFriendD = Function;
724 PrevDecl = Function->getPreviousDeclaration();
725 }
726 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
727 if (!Owner->isDependentContext() && !PrevDecl)
728 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
729
730 if (!TemplateParams)
731 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
732 }
733
Douglas Gregore53060f2009-06-25 22:08:12 +0000734 return Function;
735}
736
Douglas Gregord60e1052009-08-27 16:57:43 +0000737Decl *
738TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
739 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000740 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
741 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000742 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000743 // We are creating a function template specialization from a function
744 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000745 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000746 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000747 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000748 TemplateArgs.getInnermost().getFlatArgumentList(),
749 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000750 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000751
752 FunctionTemplateSpecializationInfo *Info
753 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000754 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Douglas Gregor6b906862009-08-21 00:16:32 +0000756 // If we already have a function template specialization, return it.
757 if (Info)
758 return Info->Function;
759 }
760
Douglas Gregor550d9b22009-10-31 17:21:17 +0000761 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000762
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000763 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000764 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000765 if (T.isNull())
766 return 0;
767
768 // Build the instantiated method declaration.
769 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000770 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Douglas Gregordec06662009-08-21 18:42:58 +0000772 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000773 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000774 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
775 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
776 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000777 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
778 Constructor->getLocation(),
779 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000780 Constructor->getDeclaratorInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000781 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000782 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000783 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
784 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
785 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
786 SemaRef.Context.getCanonicalType(ClassTy));
787 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
788 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000789 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000790 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000791 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000792 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000793 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000794 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
795 ConvTy);
796 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
797 Conversion->getLocation(), Name,
798 T, Conversion->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000799 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000800 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000801 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000802 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000803 D->getDeclName(), T, D->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000804 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000805 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000806
Douglas Gregord60e1052009-08-27 16:57:43 +0000807 if (TemplateParams) {
808 // Our resulting instantiation is actually a function template, since we
809 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000810 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000811 // template<typename T>
812 // struct X {
813 // template<typename U> void f(T, U);
814 // };
815 //
816 // X<int> x;
817 //
818 // We are instantiating the member template "f" within X<int>, which means
819 // substituting int for T, but leaving "f" as a member function template.
820 // Build the function template itself.
821 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
822 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000823 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000824 TemplateParams, Method);
825 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000826 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000827 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000828 } else if (FunctionTemplate) {
829 // Record this function template specialization.
830 Method->setFunctionTemplateSpecialization(SemaRef.Context,
831 FunctionTemplate,
832 &TemplateArgs.getInnermost(),
833 InsertPos);
834 } else {
835 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000836 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000837 }
838
Mike Stump1eb44332009-09-09 15:08:12 +0000839 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000840 // out-of-line, the instantiation will have the same lexical
841 // context (which will be a namespace scope) as the template.
842 if (D->isOutOfLine())
843 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Douglas Gregor5545e162009-03-24 00:38:23 +0000845 // Attach the parameters
846 for (unsigned P = 0; P < Params.size(); ++P)
847 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000848 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000849
850 if (InitMethodInstantiation(Method, D))
851 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000852
John McCall68263142009-11-18 22:49:29 +0000853 LookupResult Previous(SemaRef, Name, SourceLocation(),
854 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Douglas Gregord60e1052009-08-27 16:57:43 +0000856 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000857 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Douglas Gregordec06662009-08-21 18:42:58 +0000859 // In C++, the previous declaration we find might be a tag type
860 // (class or enum). In this case, the new declaration will hide the
861 // tag type. Note that this does does not apply if we're declaring a
862 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000863 if (Previous.isSingleTagDecl())
864 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000865 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000866
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000867 bool Redeclaration = false;
868 bool OverloadableAttrRequired = false;
John McCall68263142009-11-18 22:49:29 +0000869 SemaRef.CheckFunctionDeclaration(Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000870 /*FIXME:*/OverloadableAttrRequired);
871
Douglas Gregor4ba31362009-12-01 17:24:26 +0000872 if (D->isPure())
873 SemaRef.CheckPureMethod(Method, SourceRange());
874
John McCall68263142009-11-18 22:49:29 +0000875 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000876 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000877 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000879 return Method;
880}
881
Douglas Gregor615c5d42009-03-24 16:43:20 +0000882Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000883 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000884}
885
Douglas Gregor03b2b072009-03-24 00:15:49 +0000886Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000887 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000888}
889
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000890Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000891 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000892}
893
Douglas Gregor6477b692009-03-25 15:04:13 +0000894ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000895 QualType T;
896 DeclaratorInfo *DI = D->getDeclaratorInfo();
897 if (DI) {
898 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
899 D->getDeclName());
900 if (DI) T = DI->getType();
901 } else {
902 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
903 D->getDeclName());
904 DI = 0;
905 }
906
907 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000908 return 0;
909
John McCall58e46772009-10-23 21:48:59 +0000910 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000911
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000912 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000913 ParmVarDecl *Param
914 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
915 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000916
Anders Carlsson9351c172009-08-25 03:18:48 +0000917 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000918 if (D->hasUninstantiatedDefaultArg())
919 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000920 else if (Expr *Arg = D->getDefaultArg())
921 Param->setUninstantiatedDefaultArg(Arg);
922
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000923 // Note: we don't try to instantiate function parameters until after
924 // we've instantiated the function's type. Therefore, we don't have
925 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000926 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000927 return Param;
928}
929
John McCalle29ba202009-08-20 01:44:21 +0000930Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
931 TemplateTypeParmDecl *D) {
932 // TODO: don't always clone when decls are refcounted.
933 const Type* T = D->getTypeForDecl();
934 assert(T->isTemplateTypeParmType());
935 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000936
John McCalle29ba202009-08-20 01:44:21 +0000937 TemplateTypeParmDecl *Inst =
938 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +0000939 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +0000940 TTPT->getName(),
941 D->wasDeclaredWithTypename(),
942 D->isParameterPack());
943
Douglas Gregor0f8716b2009-11-09 19:17:50 +0000944 if (D->hasDefaultArgument())
945 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +0000946
Douglas Gregor550d9b22009-10-31 17:21:17 +0000947 // Introduce this template parameter's instantiation into the instantiation
948 // scope.
949 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
950
John McCalle29ba202009-08-20 01:44:21 +0000951 return Inst;
952}
953
Douglas Gregor33642df2009-10-23 23:25:44 +0000954Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
955 NonTypeTemplateParmDecl *D) {
956 // Substitute into the type of the non-type template parameter.
957 QualType T;
958 DeclaratorInfo *DI = D->getDeclaratorInfo();
959 if (DI) {
960 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
961 D->getDeclName());
962 if (DI) T = DI->getType();
963 } else {
964 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
965 D->getDeclName());
966 DI = 0;
967 }
968 if (T.isNull())
969 return 0;
970
971 // Check that this type is acceptable for a non-type template parameter.
972 bool Invalid = false;
973 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
974 if (T.isNull()) {
975 T = SemaRef.Context.IntTy;
976 Invalid = true;
977 }
978
979 NonTypeTemplateParmDecl *Param
980 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
981 D->getDepth() - 1, D->getPosition(),
982 D->getIdentifier(), T, DI);
983 if (Invalid)
984 Param->setInvalidDecl();
985
986 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +0000987
988 // Introduce this template parameter's instantiation into the instantiation
989 // scope.
990 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +0000991 return Param;
992}
993
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000994Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +0000995TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
996 TemplateTemplateParmDecl *D) {
997 // Instantiate the template parameter list of the template template parameter.
998 TemplateParameterList *TempParams = D->getTemplateParameters();
999 TemplateParameterList *InstParams;
1000 {
1001 // Perform the actual substitution of template parameters within a new,
1002 // local instantiation scope.
1003 Sema::LocalInstantiationScope Scope(SemaRef);
1004 InstParams = SubstTemplateParams(TempParams);
1005 if (!InstParams)
1006 return NULL;
1007 }
1008
1009 // Build the template template parameter.
1010 TemplateTemplateParmDecl *Param
1011 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1012 D->getDepth() - 1, D->getPosition(),
1013 D->getIdentifier(), InstParams);
1014 Param->setDefaultArgument(D->getDefaultArgument());
1015
1016 // Introduce this template parameter's instantiation into the instantiation
1017 // scope.
1018 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1019
1020 return Param;
1021}
1022
Douglas Gregor48c32a72009-11-17 06:07:40 +00001023Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1024 // Using directives are never dependent, so they require no explicit
1025
1026 UsingDirectiveDecl *Inst
1027 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1028 D->getNamespaceKeyLocation(),
1029 D->getQualifierRange(), D->getQualifier(),
1030 D->getIdentLocation(),
1031 D->getNominatedNamespace(),
1032 D->getCommonAncestor());
1033 Owner->addDecl(Inst);
1034 return Inst;
1035}
1036
John McCall7ba107a2009-11-18 02:36:19 +00001037Decl * TemplateDeclInstantiator
1038 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001039 NestedNameSpecifier *NNS =
1040 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1041 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001042 TemplateArgs);
1043 if (!NNS)
1044 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001046 CXXScopeSpec SS;
1047 SS.setRange(D->getTargetNestedNameRange());
1048 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001049
1050 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001051 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001052 D->getUsingLoc(), SS, D->getLocation(),
1053 D->getDeclName(), 0,
1054 /*instantiation*/ true,
1055 /*typename*/ true, D->getTypenameLoc());
1056 if (UD)
1057 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
1058 D);
1059 return UD;
1060}
1061
1062Decl * TemplateDeclInstantiator
1063 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1064 NestedNameSpecifier *NNS =
1065 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1066 D->getTargetNestedNameRange(),
1067 TemplateArgs);
1068 if (!NNS)
1069 return 0;
1070
1071 CXXScopeSpec SS;
1072 SS.setRange(D->getTargetNestedNameRange());
1073 SS.setScopeRep(NNS);
1074
1075 NamedDecl *UD =
1076 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1077 D->getUsingLoc(), SS, D->getLocation(),
1078 D->getDeclName(), 0,
1079 /*instantiation*/ true,
1080 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001081 if (UD)
Mike Stump1eb44332009-09-09 15:08:12 +00001082 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
Anders Carlsson0d8df782009-08-29 19:37:28 +00001083 D);
1084 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001085}
1086
John McCallce3ff2b2009-08-25 22:02:44 +00001087Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001088 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001089 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001090 return Instantiator.Visit(D);
1091}
1092
John McCalle29ba202009-08-20 01:44:21 +00001093/// \brief Instantiates a nested template parameter list in the current
1094/// instantiation context.
1095///
1096/// \param L The parameter list to instantiate
1097///
1098/// \returns NULL if there was an error
1099TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001100TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001101 // Get errors for all the parameters before bailing out.
1102 bool Invalid = false;
1103
1104 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001105 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001106 ParamVector Params;
1107 Params.reserve(N);
1108 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1109 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001110 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001111 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001112 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001113 }
1114
1115 // Clean up if we had an error.
1116 if (Invalid) {
1117 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1118 PI != PE; ++PI)
1119 if (*PI)
1120 (*PI)->Destroy(SemaRef.Context);
1121 return NULL;
1122 }
1123
1124 TemplateParameterList *InstL
1125 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1126 L->getLAngleLoc(), &Params.front(), N,
1127 L->getRAngleLoc());
1128 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001129}
John McCalle29ba202009-08-20 01:44:21 +00001130
Douglas Gregored9c0f92009-10-29 00:04:11 +00001131/// \brief Instantiate the declaration of a class template partial
1132/// specialization.
1133///
1134/// \param ClassTemplate the (instantiated) class template that is partially
1135// specialized by the instantiation of \p PartialSpec.
1136///
1137/// \param PartialSpec the (uninstantiated) class template partial
1138/// specialization that we are instantiating.
1139///
1140/// \returns true if there was an error, false otherwise.
1141bool
1142TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1143 ClassTemplateDecl *ClassTemplate,
1144 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001145 // Create a local instantiation scope for this class template partial
1146 // specialization, which will contain the instantiations of the template
1147 // parameters.
1148 Sema::LocalInstantiationScope Scope(SemaRef);
1149
Douglas Gregored9c0f92009-10-29 00:04:11 +00001150 // Substitute into the template parameters of the class template partial
1151 // specialization.
1152 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1153 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1154 if (!InstParams)
1155 return true;
1156
1157 // Substitute into the template arguments of the class template partial
1158 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001159 const TemplateArgumentLoc *PartialSpecTemplateArgs
1160 = PartialSpec->getTemplateArgsAsWritten();
1161 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1162
John McCalld5532b62009-11-23 01:53:49 +00001163 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001164 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001165 TemplateArgumentLoc Loc;
1166 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001167 return true;
John McCalld5532b62009-11-23 01:53:49 +00001168 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001169 }
1170
1171
1172 // Check that the template argument list is well-formed for this
1173 // class template.
1174 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1175 InstTemplateArgs.size());
1176 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1177 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001178 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001179 false,
1180 Converted))
1181 return true;
1182
1183 // Figure out where to insert this class template partial specialization
1184 // in the member template's set of class template partial specializations.
1185 llvm::FoldingSetNodeID ID;
1186 ClassTemplatePartialSpecializationDecl::Profile(ID,
1187 Converted.getFlatArguments(),
1188 Converted.flatSize(),
1189 SemaRef.Context);
1190 void *InsertPos = 0;
1191 ClassTemplateSpecializationDecl *PrevDecl
1192 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1193 InsertPos);
1194
1195 // Build the canonical type that describes the converted template
1196 // arguments of the class template partial specialization.
1197 QualType CanonType
1198 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1199 Converted.getFlatArguments(),
1200 Converted.flatSize());
1201
1202 // Build the fully-sugared type for this class template
1203 // specialization as the user wrote in the specialization
1204 // itself. This means that we'll pretty-print the type retrieved
1205 // from the specialization's declaration the way that the user
1206 // actually wrote the specialization, rather than formatting the
1207 // name based on the "canonical" representation used to store the
1208 // template arguments in the specialization.
1209 QualType WrittenTy
1210 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001211 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001212 CanonType);
1213
1214 if (PrevDecl) {
1215 // We've already seen a partial specialization with the same template
1216 // parameters and template arguments. This can happen, for example, when
1217 // substituting the outer template arguments ends up causing two
1218 // class template partial specializations of a member class template
1219 // to have identical forms, e.g.,
1220 //
1221 // template<typename T, typename U>
1222 // struct Outer {
1223 // template<typename X, typename Y> struct Inner;
1224 // template<typename Y> struct Inner<T, Y>;
1225 // template<typename Y> struct Inner<U, Y>;
1226 // };
1227 //
1228 // Outer<int, int> outer; // error: the partial specializations of Inner
1229 // // have the same signature.
1230 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1231 << WrittenTy;
1232 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1233 << SemaRef.Context.getTypeDeclType(PrevDecl);
1234 return true;
1235 }
1236
1237
1238 // Create the class template partial specialization declaration.
1239 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1240 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1241 PartialSpec->getLocation(),
1242 InstParams,
1243 ClassTemplate,
1244 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001245 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001246 0);
1247 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1248 InstPartialSpec->setTypeAsWritten(WrittenTy);
1249
1250 // Add this partial specialization to the set of class template partial
1251 // specializations.
1252 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1253 InsertPos);
1254 return false;
1255}
1256
John McCallce3ff2b2009-08-25 22:02:44 +00001257/// \brief Does substitution on the type of the given function, including
1258/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001259///
John McCallce3ff2b2009-08-25 22:02:44 +00001260/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001261///
1262/// \param Params the instantiated parameter declarations
1263
John McCallce3ff2b2009-08-25 22:02:44 +00001264/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001265/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001266QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001267TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001268 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1269 bool InvalidDecl = false;
1270
John McCallce3ff2b2009-08-25 22:02:44 +00001271 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001272 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001273 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001274 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001275 PEnd = D->param_end();
1276 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001277 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001278 if (PInst->getType()->isVoidType()) {
1279 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1280 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001281 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001282 PInst->getType(),
1283 diag::err_abstract_type_in_decl,
1284 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001285 PInst->setInvalidDecl();
1286
1287 Params.push_back(PInst);
1288 ParamTys.push_back(PInst->getType());
1289
1290 if (PInst->isInvalidDecl())
1291 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001292 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001293 InvalidDecl = true;
1294 }
1295
1296 // FIXME: Deallocate dead declarations.
1297 if (InvalidDecl)
1298 return QualType();
1299
John McCall183700f2009-09-21 23:43:11 +00001300 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001301 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001302 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001303 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1304 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001305 if (ResultType.isNull())
1306 return QualType();
1307
Jay Foadbeaaccd2009-05-21 09:52:38 +00001308 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001309 Proto->isVariadic(), Proto->getTypeQuals(),
1310 D->getLocation(), D->getDeclName());
1311}
1312
Mike Stump1eb44332009-09-09 15:08:12 +00001313/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001314/// declaration (New) from the corresponding fields of its template (Tmpl).
1315///
1316/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001317bool
1318TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001319 FunctionDecl *Tmpl) {
1320 if (Tmpl->isDeleted())
1321 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Douglas Gregorcca9e962009-07-01 22:01:06 +00001323 // If we are performing substituting explicitly-specified template arguments
1324 // or deduced template arguments into a function template and we reach this
1325 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001326 // to keeping the new function template specialization. We therefore
1327 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001328 // into a template instantiation for this specific function template
1329 // specialization, which is not a SFINAE context, so that we diagnose any
1330 // further errors in the declaration itself.
1331 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1332 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1333 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1334 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001335 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001336 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001337 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001338 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001339 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001340 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1341 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001342 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001343 }
1344 }
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Douglas Gregore53060f2009-06-25 22:08:12 +00001346 return false;
1347}
1348
Douglas Gregor5545e162009-03-24 00:38:23 +00001349/// \brief Initializes common fields of an instantiated method
1350/// declaration (New) from the corresponding fields of its template
1351/// (Tmpl).
1352///
1353/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001354bool
1355TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001356 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001357 if (InitFunctionInstantiation(New, Tmpl))
1358 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Douglas Gregor5545e162009-03-24 00:38:23 +00001360 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1361 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001362 if (Tmpl->isVirtualAsWritten())
1363 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001364
1365 // FIXME: attributes
1366 // FIXME: New needs a pointer to Tmpl
1367 return false;
1368}
Douglas Gregora58861f2009-05-13 20:28:22 +00001369
1370/// \brief Instantiate the definition of the given function from its
1371/// template.
1372///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001373/// \param PointOfInstantiation the point at which the instantiation was
1374/// required. Note that this is not precisely a "point of instantiation"
1375/// for the function, but it's close.
1376///
Douglas Gregora58861f2009-05-13 20:28:22 +00001377/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001378/// function template specialization or member function of a class template
1379/// specialization.
1380///
1381/// \param Recursive if true, recursively instantiates any functions that
1382/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001383///
1384/// \param DefinitionRequired if true, then we are performing an explicit
1385/// instantiation where the body of the function is required. Complain if
1386/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001387void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001388 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001389 bool Recursive,
1390 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001391 if (Function->isInvalidDecl())
1392 return;
1393
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001394 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001396 // Never instantiate an explicit specialization.
1397 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1398 return;
1399
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001400 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001401 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001402 Stmt *Pattern = 0;
1403 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001404 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001405
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001406 if (!Pattern) {
1407 if (DefinitionRequired) {
1408 if (Function->getPrimaryTemplate())
1409 Diag(PointOfInstantiation,
1410 diag::err_explicit_instantiation_undefined_func_template)
1411 << Function->getPrimaryTemplate();
1412 else
1413 Diag(PointOfInstantiation,
1414 diag::err_explicit_instantiation_undefined_member)
1415 << 1 << Function->getDeclName() << Function->getDeclContext();
1416
1417 if (PatternDecl)
1418 Diag(PatternDecl->getLocation(),
1419 diag::note_explicit_instantiation_here);
1420 }
1421
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001422 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001423 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001424
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001425 // C++0x [temp.explicit]p9:
1426 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001427 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001428 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001429 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001430 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001431 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001432 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001434 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1435 if (Inst)
1436 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001437
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001438 // If we're performing recursive template instantiation, create our own
1439 // queue of pending implicit instantiations that we will instantiate later,
1440 // while we're still within our own instantiation context.
1441 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1442 if (Recursive)
1443 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001445 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1446
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001447 // Introduce a new scope where local variable instantiations will be
1448 // recorded.
1449 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001451 // Introduce the instantiated function parameters into the local
1452 // instantiation scope.
1453 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1454 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1455 Function->getParamDecl(I));
1456
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001457 // Enter the scope of this instantiation. We don't use
1458 // PushDeclContext because we don't have a scope.
1459 DeclContext *PreviousContext = CurContext;
1460 CurContext = Function;
1461
Mike Stump1eb44332009-09-09 15:08:12 +00001462 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001463 getTemplateInstantiationArgs(Function);
1464
1465 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001466 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001467 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1468 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1469 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001470 }
1471
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001472 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001473 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001474
Douglas Gregor52604ab2009-09-11 21:19:12 +00001475 if (Body.isInvalid())
1476 Function->setInvalidDecl();
1477
Mike Stump1eb44332009-09-09 15:08:12 +00001478 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001479 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001480
1481 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001482
1483 DeclGroupRef DG(Function);
1484 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001486 if (Recursive) {
1487 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001488 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001489 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001491 // Restore the set of pending implicit instantiations.
1492 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1493 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001494}
1495
1496/// \brief Instantiate the definition of the given variable from its
1497/// template.
1498///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001499/// \param PointOfInstantiation the point at which the instantiation was
1500/// required. Note that this is not precisely a "point of instantiation"
1501/// for the function, but it's close.
1502///
1503/// \param Var the already-instantiated declaration of a static member
1504/// variable of a class template specialization.
1505///
1506/// \param Recursive if true, recursively instantiates any functions that
1507/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001508///
1509/// \param DefinitionRequired if true, then we are performing an explicit
1510/// instantiation where an out-of-line definition of the member variable
1511/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001512void Sema::InstantiateStaticDataMemberDefinition(
1513 SourceLocation PointOfInstantiation,
1514 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001515 bool Recursive,
1516 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001517 if (Var->isInvalidDecl())
1518 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Douglas Gregor7caa6822009-07-24 20:34:43 +00001520 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001521 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001522 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001523 assert(Def->isStaticDataMember() && "Not a static data member?");
1524 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Douglas Gregor0d035142009-10-27 18:42:08 +00001526 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001527 // We did not find an out-of-line definition of this static data member,
1528 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001529 // instantiate this definition (or provide a specialization for it) in
1530 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001531 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001532 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001533 Diag(PointOfInstantiation,
1534 diag::err_explicit_instantiation_undefined_member)
1535 << 2 << Var->getDeclName() << Var->getDeclContext();
1536 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1537 }
1538
Douglas Gregor7caa6822009-07-24 20:34:43 +00001539 return;
1540 }
1541
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001542 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001543 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001544 return;
1545
1546 // C++0x [temp.explicit]p9:
1547 // Except for inline functions, other explicit instantiation declarations
1548 // have the effect of suppressing the implicit instantiation of the entity
1549 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001550 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001551 == TSK_ExplicitInstantiationDeclaration)
1552 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Douglas Gregor7caa6822009-07-24 20:34:43 +00001554 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1555 if (Inst)
1556 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Douglas Gregor7caa6822009-07-24 20:34:43 +00001558 // If we're performing recursive template instantiation, create our own
1559 // queue of pending implicit instantiations that we will instantiate later,
1560 // while we're still within our own instantiation context.
1561 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1562 if (Recursive)
1563 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Douglas Gregor7caa6822009-07-24 20:34:43 +00001565 // Enter the scope of this instantiation. We don't use
1566 // PushDeclContext because we don't have a scope.
1567 DeclContext *PreviousContext = CurContext;
1568 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001570 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001571 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001572 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001573 CurContext = PreviousContext;
1574
1575 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001576 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001577 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1578 assert(MSInfo && "Missing member specialization information?");
1579 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1580 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001581 DeclGroupRef DG(Var);
1582 Consumer.HandleTopLevelDecl(DG);
1583 }
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Douglas Gregor7caa6822009-07-24 20:34:43 +00001585 if (Recursive) {
1586 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001587 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001588 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Douglas Gregor7caa6822009-07-24 20:34:43 +00001590 // Restore the set of pending implicit instantiations.
1591 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001592 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001593}
Douglas Gregor815215d2009-05-27 05:35:12 +00001594
Anders Carlsson09025312009-08-29 05:16:22 +00001595void
1596Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1597 const CXXConstructorDecl *Tmpl,
1598 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Anders Carlsson09025312009-08-29 05:16:22 +00001600 llvm::SmallVector<MemInitTy*, 4> NewInits;
1601
1602 // Instantiate all the initializers.
1603 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001604 InitsEnd = Tmpl->init_end();
1605 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001606 CXXBaseOrMemberInitializer *Init = *Inits;
1607
1608 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Anders Carlsson09025312009-08-29 05:16:22 +00001610 // Instantiate all the arguments.
1611 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1612 Args != ArgsEnd; ++Args) {
1613 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1614
1615 if (NewArg.isInvalid())
1616 New->setInvalidDecl();
1617 else
1618 NewArgs.push_back(NewArg.takeAs<Expr>());
1619 }
1620
1621 MemInitResult NewInit;
1622
1623 if (Init->isBaseInitializer()) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001624 DeclaratorInfo *BaseDInfo = SubstType(Init->getBaseClassInfo(),
1625 TemplateArgs,
1626 Init->getSourceLocation(),
1627 New->getDeclName());
1628 if (!BaseDInfo) {
1629 New->setInvalidDecl();
1630 continue;
1631 }
1632
1633 NewInit = BuildBaseInitializer(BaseDInfo->getType(), BaseDInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001634 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001635 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001636 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001637 Init->getRParenLoc(),
1638 New->getParent());
1639 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001640 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001642 // Is this an anonymous union?
1643 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001644 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001645 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001646 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1647 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001648
1649 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001650 NewArgs.size(),
1651 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001652 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001653 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 Gregor815215d2009-05-27 05:35:12 +00001890 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00001891 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
1892 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
1893 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001894 // D is a local of some kind. Look into the map of local
1895 // declarations to their instantiations.
1896 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1897 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001898
Douglas Gregore95b4092009-09-16 18:34:49 +00001899 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1900 if (!Record->isDependentContext())
1901 return D;
1902
1903 // If the RecordDecl is actually the injected-class-name or a "templated"
1904 // declaration for a class template or class template partial
1905 // specialization, substitute into the injected-class-name of the
1906 // class template or partial specialization to find the new DeclContext.
1907 QualType T;
1908 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1909
1910 if (ClassTemplate) {
1911 T = ClassTemplate->getInjectedClassNameType(Context);
1912 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1913 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1914 T = Context.getTypeDeclType(Record);
1915 ClassTemplate = PartialSpec->getSpecializedTemplate();
1916 }
1917
1918 if (!T.isNull()) {
1919 // Substitute into the injected-class-name to get the type corresponding
1920 // to the instantiation we want. This substitution should never fail,
1921 // since we know we can instantiate the injected-class-name or we wouldn't
1922 // have gotten to the injected-class-name!
1923 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1924 // instantiation in the common case?
1925 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1926 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1927
1928 if (!T->isDependentType()) {
1929 assert(T->isRecordType() && "Instantiation must produce a record type");
1930 return T->getAs<RecordType>()->getDecl();
1931 }
1932
1933 // We are performing "partial" template instantiation to create the
1934 // member declarations for the members of a class template
1935 // specialization. Therefore, D is actually referring to something in
1936 // the current instantiation. Look through the current context,
1937 // which contains actual instantiations, to find the instantiation of
1938 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00001939 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00001940 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001941 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00001942 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00001943 if (isInstantiationOf(ClassTemplate,
1944 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00001945 return Spec;
1946 }
1947
Mike Stump1eb44332009-09-09 15:08:12 +00001948 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00001949 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00001950 return Record;
John McCall52a575a2009-08-29 08:11:13 +00001951 }
Douglas Gregore95b4092009-09-16 18:34:49 +00001952
1953 // Fall through to deal with other dependent record types (e.g.,
1954 // anonymous unions in class templates).
1955 }
John McCall52a575a2009-08-29 08:11:13 +00001956
Douglas Gregore95b4092009-09-16 18:34:49 +00001957 if (!ParentDC->isDependentContext())
1958 return D;
1959
1960 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001961 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00001962 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Douglas Gregor815215d2009-05-27 05:35:12 +00001964 if (ParentDC != D->getDeclContext()) {
1965 // We performed some kind of instantiation in the parent context,
1966 // so now we need to look into the instantiated parent context to
1967 // find the instantiation of the declaration D.
1968 NamedDecl *Result = 0;
1969 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001970 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001971 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1972 } else {
1973 // Since we don't have a name for the entity we're looking for,
1974 // our only option is to walk through all of the declarations to
1975 // find that name. This will occur in a few cases:
1976 //
1977 // - anonymous struct/union within a template
1978 // - unnamed class/struct/union/enum within a template
1979 //
1980 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00001981 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001982 ParentDC->decls_begin(),
1983 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor815215d2009-05-27 05:35:12 +00001986 assert(Result && "Unable to find instantiation of declaration!");
1987 D = Result;
1988 }
1989
Douglas Gregor815215d2009-05-27 05:35:12 +00001990 return D;
1991}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001992
Mike Stump1eb44332009-09-09 15:08:12 +00001993/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001994/// instantiations we have seen until this point.
1995void Sema::PerformPendingImplicitInstantiations() {
1996 while (!PendingImplicitInstantiations.empty()) {
1997 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001998 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Douglas Gregor7caa6822009-07-24 20:34:43 +00002000 // Instantiate function definitions
2001 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002002 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002003 Function->getLocation(), *this,
2004 Context.getSourceManager(),
2005 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002007 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002008 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002009 continue;
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Douglas Gregor7caa6822009-07-24 20:34:43 +00002012 // Instantiate static data member definitions.
2013 VarDecl *Var = cast<VarDecl>(Inst.first);
2014 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002015
Mike Stump1eb44332009-09-09 15:08:12 +00002016 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002017 Var->getLocation(), *this,
2018 Context.getSourceManager(),
2019 "instantiating static data member "
2020 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Douglas Gregor7caa6822009-07-24 20:34:43 +00002022 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002023 }
2024}