blob: 23a9430d746f3651c8e865fd28e21ea403a1c01b [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"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000020#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000022
23using namespace clang;
24
25namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000026 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000027 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028 Sema &SemaRef;
29 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000030 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Anders Carlssond8fe2d52009-11-07 06:07:58 +000032 void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
43 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000046 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000047 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitFieldDecl(FieldDecl *D);
49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000052 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000053 Decl *VisitFunctionDecl(FunctionDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000055 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000056 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000058 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000059 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000060 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000061 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000062 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000063 Decl *VisitClassTemplatePartialSpecializationDecl(
64 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000065 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000067 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000068 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000069 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000070 Decl *VisitUsingDecl(UsingDecl *D);
71 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000072 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
73 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor8dbc2692009-03-17 21:15:40 +000075 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000076 Decl *VisitDecl(Decl *D) {
77 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
78 Diagnostic::Error,
79 "cannot instantiate %0 yet");
80 SemaRef.Diag(D->getLocation(), DiagID)
81 << D->getDeclKindName();
82
Douglas Gregor8dbc2692009-03-17 21:15:40 +000083 return 0;
84 }
Douglas Gregor5545e162009-03-24 00:38:23 +000085
John McCallfd810b12009-08-14 02:03:10 +000086 const LangOptions &getLangOptions() {
87 return SemaRef.getLangOptions();
88 }
89
Douglas Gregor5545e162009-03-24 00:38:23 +000090 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000091 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000092 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000093 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000094 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000095
96 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000097 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000098
99 bool InstantiateClassTemplatePartialSpecialization(
100 ClassTemplateDecl *ClassTemplate,
101 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000102 };
103}
104
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000105// FIXME: Is this too simple?
106void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
107 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
108 TmplAttr = TmplAttr->getNext()) {
109
110 // FIXME: Is cloning correct for all attributes?
111 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
112
113 New->addAttr(NewAttr);
114 }
115}
116
Douglas Gregor4f722be2009-03-25 15:45:12 +0000117Decl *
118TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
119 assert(false && "Translation units cannot be instantiated");
120 return D;
121}
122
123Decl *
124TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
125 assert(false && "Namespaces cannot be instantiated");
126 return D;
127}
128
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000129Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
130 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000131 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000132 if (DI->getType()->isDependentType()) {
133 DI = SemaRef.SubstType(DI, TemplateArgs,
134 D->getLocation(), D->getDeclName());
135 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000136 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000137 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 }
139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000141 // Create the new typedef
142 TypedefDecl *Typedef
143 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000144 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 if (Invalid)
146 Typedef->setInvalidDecl();
147
John McCall5126fd02009-12-30 00:31:22 +0000148 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
149 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Prev, TemplateArgs);
150 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
151 }
152
John McCall46460a62010-01-20 21:53:11 +0000153 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000154 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000156 return Typedef;
157}
158
Douglas Gregor6eef5192009-12-14 19:27:10 +0000159/// \brief Instantiate the arguments provided as part of initialization.
160///
161/// \returns true if an error occurred, false otherwise.
162static bool InstantiateInitializationArguments(Sema &SemaRef,
163 Expr **Args, unsigned NumArgs,
164 const MultiLevelTemplateArgumentList &TemplateArgs,
165 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
166 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
167 for (unsigned I = 0; I != NumArgs; ++I) {
168 // When we hit the first defaulted argument, break out of the loop:
169 // we don't pass those default arguments on.
170 if (Args[I]->isDefaultArgument())
171 break;
172
173 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
174 if (Arg.isInvalid())
175 return true;
176
177 Expr *ArgExpr = (Expr *)Arg.get();
178 InitArgs.push_back(Arg.release());
179
180 // FIXME: We're faking all of the comma locations. Do we need them?
181 FakeCommaLocs.push_back(
182 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
183 }
184
185 return false;
186}
187
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000188Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000189 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000190 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000191 TemplateArgs,
192 D->getTypeSpecStartLoc(),
193 D->getDeclName());
194 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000195 return 0;
196
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000197 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000198 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
199 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000200 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000201 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000202 Var->setThreadSpecified(D->isThreadSpecified());
203 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
204 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000205
206 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000207 // out-of-line, the instantiation will have the same lexical
208 // context (which will be a namespace scope) as the template.
209 if (D->isOutOfLine())
210 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000211
John McCall46460a62010-01-20 21:53:11 +0000212 Var->setAccess(D->getAccess());
213
Mike Stump390b4cc2009-05-16 07:39:55 +0000214 // FIXME: In theory, we could have a previous declaration for variables that
215 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000216 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000217 // FIXME: having to fake up a LookupResult is dumb.
218 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
219 Sema::LookupOrdinaryName);
220 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Douglas Gregor7caa6822009-07-24 20:34:43 +0000222 if (D->isOutOfLine()) {
223 D->getLexicalDeclContext()->addDecl(Var);
224 Owner->makeDeclVisibleInContext(Var);
225 } else {
226 Owner->addDecl(Var);
227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000229 // Link instantiations of static data members back to the template from
230 // which they were instantiated.
231 if (Var->isStaticDataMember())
232 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000233 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000234
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000235 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000236 if (Var->isStaticDataMember() && !D->isOutOfLine())
237 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
238 else
239 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
240
Douglas Gregor6eef5192009-12-14 19:27:10 +0000241 // Extract the initializer, skipping through any temporary-binding
242 // expressions and look at the subexpression as it was written.
243 Expr *DInit = D->getInit();
244 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
245 DInit = Binder->getSubExpr();
246 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
247 DInit = ICE->getSubExprAsWritten();
248
249 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
250 // The initializer is a parenthesized list of expressions that is
251 // type-dependent. Instantiate each of the expressions; we'll be
252 // performing direct initialization with them.
253 llvm::SmallVector<SourceLocation, 4> CommaLocs;
254 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
255 if (!InstantiateInitializationArguments(SemaRef,
256 PLE->getExprs(),
257 PLE->getNumExprs(),
258 TemplateArgs,
259 CommaLocs, InitArgs)) {
260 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000261 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000262 PLE->getLParenLoc(),
263 move_arg(InitArgs),
264 CommaLocs.data(),
265 PLE->getRParenLoc());
266 }
267 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
268 // The initializer resolved to a constructor. Instantiate the constructor
269 // arguments.
270 llvm::SmallVector<SourceLocation, 4> CommaLocs;
271 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
272
273 if (!InstantiateInitializationArguments(SemaRef,
274 Construct->getArgs(),
275 Construct->getNumArgs(),
276 TemplateArgs,
277 CommaLocs, InitArgs)) {
278 if (D->hasCXXDirectInitializer()) {
279 SourceLocation FakeLParenLoc =
280 SemaRef.PP.getLocForEndOfToken(D->getLocation());
281 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
282 : CommaLocs.back();
283 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
284 FakeLParenLoc,
285 move_arg(InitArgs),
286 CommaLocs.data(),
287 FakeRParenLoc);
288 } else if (InitArgs.size() == 1) {
289 Expr *Init = (Expr*)(InitArgs.take()[0]);
290 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
291 SemaRef.Owned(Init),
292 false);
293 } else {
294 assert(InitArgs.size() == 0);
295 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
296 }
297 }
298 } else {
299 OwningExprResult Init
300 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
301
302 // FIXME: Not happy about invalidating decls just because of a bad
303 // initializer, unless it affects the type.
304 if (Init.isInvalid())
305 Var->setInvalidDecl();
306 else
307 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
308 D->hasCXXDirectInitializer());
309 }
310
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000311 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000312 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
313 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000314
315 return Var;
316}
317
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000318Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
319 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000320 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000321 if (DI->getType()->isDependentType()) {
322 DI = SemaRef.SubstType(DI, TemplateArgs,
323 D->getLocation(), D->getDeclName());
324 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000325 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000326 Invalid = true;
327 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000328 // C++ [temp.arg.type]p3:
329 // If a declaration acquires a function type through a type
330 // dependent on a template-parameter and this causes a
331 // declaration that does not use the syntactic form of a
332 // function declarator to have function type, the program is
333 // ill-formed.
334 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000335 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000336 Invalid = true;
337 }
338 }
339
340 Expr *BitWidth = D->getBitWidth();
341 if (Invalid)
342 BitWidth = 0;
343 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000344 // The bit-width expression is not potentially evaluated.
345 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000347 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000348 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000349 if (InstantiatedBitWidth.isInvalid()) {
350 Invalid = true;
351 BitWidth = 0;
352 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000353 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000354 }
355
John McCall07fb6be2009-10-22 23:33:21 +0000356 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
357 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000358 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000359 D->getLocation(),
360 D->isMutable(),
361 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000362 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000363 D->getAccess(),
364 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000365 if (!Field) {
366 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000367 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000370 InstantiateAttrs(D, Field);
371
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000372 if (Invalid)
373 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000375 if (!Field->getDeclName()) {
376 // Keep track of where this decl came from.
377 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000378 }
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000380 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000381 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000382 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383
384 return Field;
385}
386
John McCall02cace72009-08-28 07:59:38 +0000387Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
388 FriendDecl::FriendUnion FU;
389
390 // Handle friend type expressions by simply substituting template
391 // parameters into the pattern type.
392 if (Type *Ty = D->getFriendType()) {
393 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
394 D->getLocation(), DeclarationName());
395 if (T.isNull()) return 0;
396
397 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
398 FU = T.getTypePtr();
399
400 // Handle everything else by appropriate substitution.
401 } else {
402 NamedDecl *ND = D->getFriendDecl();
403 assert(ND && "friend decl must be a decl or a type!");
404
Douglas Gregora735b202009-10-13 14:39:41 +0000405 // FIXME: We have a problem here, because the nested call to Visit(ND)
406 // will inject the thing that the friend references into the current
407 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000408 Decl *NewND;
409
410 // Hack to make this work almost well pending a rewrite.
411 if (ND->getDeclContext()->isRecord())
412 NewND = SemaRef.FindInstantiatedDecl(ND, TemplateArgs);
Douglas Gregor7557a132009-12-24 20:56:24 +0000413 else if (D->wasSpecialization()) {
414 // Totally egregious hack to work around PR5866
415 return 0;
416 } else
John McCalle129d442009-12-17 23:21:11 +0000417 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000418 if (!NewND) return 0;
419
420 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000421 }
Mike Stump1eb44332009-09-09 15:08:12 +0000422
John McCall02cace72009-08-28 07:59:38 +0000423 FriendDecl *FD =
424 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
425 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000426 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000427 Owner->addDecl(FD);
428 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000429}
430
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000431Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
432 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Douglas Gregorac7610d2009-06-22 20:57:11 +0000434 // The expression in a static assertion is not potentially evaluated.
435 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000437 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000438 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000439 if (InstantiatedAssertExpr.isInvalid())
440 return 0;
441
Douglas Gregor43d9d922009-08-08 01:41:12 +0000442 OwningExprResult Message(SemaRef, D->getMessage());
443 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000444 Decl *StaticAssert
445 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000446 move(InstantiatedAssertExpr),
447 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000448 return StaticAssert;
449}
450
451Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000452 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000453 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000454 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000456 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000457 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000458 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000459 Enum->startDefinition();
460
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000461 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000462
463 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000464 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
465 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000466 EC != ECEnd; ++EC) {
467 // The specified value for the enumerator.
468 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000469 if (Expr *UninstValue = EC->getInitExpr()) {
470 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000471 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000472 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000473
John McCallce3ff2b2009-08-25 22:02:44 +0000474 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000475 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000476
477 // Drop the initial value and continue.
478 bool isInvalid = false;
479 if (Value.isInvalid()) {
480 Value = SemaRef.Owned((Expr *)0);
481 isInvalid = true;
482 }
483
Mike Stump1eb44332009-09-09 15:08:12 +0000484 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000485 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
486 EC->getLocation(), EC->getIdentifier(),
487 move(Value));
488
489 if (isInvalid) {
490 if (EnumConst)
491 EnumConst->setInvalidDecl();
492 Enum->setInvalidDecl();
493 }
494
495 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000496 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000497 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000498 LastEnumConst = EnumConst;
499 }
500 }
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000502 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000503 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000504 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
505 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000506 &Enumerators[0], Enumerators.size(),
507 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000508
509 return Enum;
510}
511
Douglas Gregor6477b692009-03-25 15:04:13 +0000512Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
513 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
514 return 0;
515}
516
Douglas Gregored9c0f92009-10-29 00:04:11 +0000517namespace {
518 class SortDeclByLocation {
519 SourceManager &SourceMgr;
520
521 public:
522 explicit SortDeclByLocation(SourceManager &SourceMgr)
523 : SourceMgr(SourceMgr) { }
524
525 bool operator()(const Decl *X, const Decl *Y) const {
526 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
527 Y->getLocation());
528 }
529 };
530}
531
John McCalle29ba202009-08-20 01:44:21 +0000532Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000533 // Create a local instantiation scope for this class template, which
534 // will contain the instantiations of the template parameters.
535 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000536 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000537 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000538 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000539 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000540
541 CXXRecordDecl *Pattern = D->getTemplatedDecl();
542 CXXRecordDecl *RecordInst
543 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
544 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000545 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
546 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000547
548 ClassTemplateDecl *Inst
549 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
550 D->getIdentifier(), InstParams, RecordInst, 0);
551 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000552 if (D->getFriendObjectKind())
553 Inst->setObjectOfFriendDecl(true);
554 else
555 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000556 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000557
558 // Trigger creation of the type for the instantiation.
559 SemaRef.Context.getTypeDeclType(RecordInst);
560
Douglas Gregor259571e2009-10-30 22:42:42 +0000561 // Finish handling of friends.
562 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000563 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000564 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000565
John McCall46460a62010-01-20 21:53:11 +0000566 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000567 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000568
569 // First, we sort the partial specializations by location, so
570 // that we instantiate them in the order they were declared.
571 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
572 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
573 P = D->getPartialSpecializations().begin(),
574 PEnd = D->getPartialSpecializations().end();
575 P != PEnd; ++P)
576 PartialSpecs.push_back(&*P);
577 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
578 SortDeclByLocation(SemaRef.SourceMgr));
579
580 // Instantiate all of the partial specializations of this member class
581 // template.
582 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
583 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
584
John McCalle29ba202009-08-20 01:44:21 +0000585 return Inst;
586}
587
Douglas Gregord60e1052009-08-27 16:57:43 +0000588Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000589TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
590 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000591 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
592
593 // Lookup the already-instantiated declaration in the instantiation
594 // of the class template and return that.
595 DeclContext::lookup_result Found
596 = Owner->lookup(ClassTemplate->getDeclName());
597 if (Found.first == Found.second)
598 return 0;
599
600 ClassTemplateDecl *InstClassTemplate
601 = dyn_cast<ClassTemplateDecl>(*Found.first);
602 if (!InstClassTemplate)
603 return 0;
604
605 Decl *DCanon = D->getCanonicalDecl();
606 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
607 P = InstClassTemplate->getPartialSpecializations().begin(),
608 PEnd = InstClassTemplate->getPartialSpecializations().end();
609 P != PEnd; ++P) {
610 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
611 return &*P;
612 }
613
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000614 return 0;
615}
616
617Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000618TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000619 // Create a local instantiation scope for this function template, which
620 // will contain the instantiations of the template parameters and then get
621 // merged with the local instantiation scope for the function template
622 // itself.
623 Sema::LocalInstantiationScope Scope(SemaRef);
624
Douglas Gregord60e1052009-08-27 16:57:43 +0000625 TemplateParameterList *TempParams = D->getTemplateParameters();
626 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000627 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000628 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000629
Douglas Gregora735b202009-10-13 14:39:41 +0000630 FunctionDecl *Instantiated = 0;
631 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
632 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
633 InstParams));
634 else
635 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
636 D->getTemplatedDecl(),
637 InstParams));
638
639 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000640 return 0;
641
John McCall46460a62010-01-20 21:53:11 +0000642 Instantiated->setAccess(D->getAccess());
643
Mike Stump1eb44332009-09-09 15:08:12 +0000644 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000645 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000646 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000647 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000648 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000649 assert(InstTemplate &&
650 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000651
652 // Link the instantiation back to the pattern *unless* this is a
653 // non-definition friend declaration.
654 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
655 !(InstTemplate->getFriendObjectKind() &&
656 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000657 InstTemplate->setInstantiatedFromMemberTemplate(D);
658
659 // Add non-friends into the owner.
660 if (!InstTemplate->getFriendObjectKind())
661 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000662 return InstTemplate;
663}
664
Douglas Gregord475b8d2009-03-25 21:17:03 +0000665Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
666 CXXRecordDecl *PrevDecl = 0;
667 if (D->isInjectedClassName())
668 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000669 else if (D->getPreviousDeclaration()) {
670 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
671 TemplateArgs);
672 if (!Prev) return 0;
673 PrevDecl = cast<CXXRecordDecl>(Prev);
674 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000675
676 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000677 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000678 D->getLocation(), D->getIdentifier(),
679 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000680 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000681 // FIXME: Check against AS_none is an ugly hack to work around the issue that
682 // the tag decls introduced by friend class declarations don't have an access
683 // specifier. Remove once this area of the code gets sorted out.
684 if (D->getAccess() != AS_none)
685 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000686 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000687 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000688
John McCall02cace72009-08-28 07:59:38 +0000689 // If the original function was part of a friend declaration,
690 // inherit its namespace state.
691 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
692 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
693
Anders Carlssond8b285f2009-09-01 04:26:58 +0000694 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
695
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000696 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000697 return Record;
698}
699
John McCall02cace72009-08-28 07:59:38 +0000700/// Normal class members are of more specific types and therefore
701/// don't make it here. This function serves two purposes:
702/// 1) instantiating function templates
703/// 2) substituting friend declarations
704/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000705Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000706 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000707 // Check whether there is already a function template specialization for
708 // this declaration.
709 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
710 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000711 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000712 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000713 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000714 TemplateArgs.getInnermost().getFlatArgumentList(),
715 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000716 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000717
718 FunctionTemplateSpecializationInfo *Info
719 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000720 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Douglas Gregor127102b2009-06-29 20:59:39 +0000722 // If we already have a function template specialization, return it.
723 if (Info)
724 return Info->Function;
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Douglas Gregor79c22782010-01-16 20:21:20 +0000727 bool MergeWithParentScope = (TemplateParams != 0) ||
728 !(isa<Decl>(Owner) &&
729 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
730 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Douglas Gregore53060f2009-06-25 22:08:12 +0000732 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000733 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000734 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000735 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000736
Douglas Gregore53060f2009-06-25 22:08:12 +0000737 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000738 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
739 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000740 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000741 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000742 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000743 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000744 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000745 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Douglas Gregore53060f2009-06-25 22:08:12 +0000747 // Attach the parameters
748 for (unsigned P = 0; P < Params.size(); ++P)
749 Params[P]->setOwningFunction(Function);
750 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000751
Douglas Gregora735b202009-10-13 14:39:41 +0000752 if (TemplateParams) {
753 // Our resulting instantiation is actually a function template, since we
754 // are substituting only the outer template parameters. For example, given
755 //
756 // template<typename T>
757 // struct X {
758 // template<typename U> friend void f(T, U);
759 // };
760 //
761 // X<int> x;
762 //
763 // We are instantiating the friend function template "f" within X<int>,
764 // which means substituting int for T, but leaving "f" as a friend function
765 // template.
766 // Build the function template itself.
767 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
768 Function->getLocation(),
769 Function->getDeclName(),
770 TemplateParams, Function);
771 Function->setDescribedFunctionTemplate(FunctionTemplate);
772 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000773 } else if (FunctionTemplate) {
774 // Record this function template specialization.
775 Function->setFunctionTemplateSpecialization(SemaRef.Context,
776 FunctionTemplate,
777 &TemplateArgs.getInnermost(),
778 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000779 }
Douglas Gregora735b202009-10-13 14:39:41 +0000780
Douglas Gregore53060f2009-06-25 22:08:12 +0000781 if (InitFunctionInstantiation(Function, D))
782 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregore53060f2009-06-25 22:08:12 +0000784 bool Redeclaration = false;
785 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000786
John McCall68263142009-11-18 22:49:29 +0000787 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
788 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
789
Douglas Gregora735b202009-10-13 14:39:41 +0000790 if (TemplateParams || !FunctionTemplate) {
791 // Look only into the namespace where the friend would be declared to
792 // find a previous declaration. This is the innermost enclosing namespace,
793 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000794 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000795
Douglas Gregora735b202009-10-13 14:39:41 +0000796 // In C++, the previous declaration we find might be a tag type
797 // (class or enum). In this case, the new declaration will hide the
798 // tag type. Note that this does does not apply if we're declaring a
799 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000800 if (Previous.isSingleTagDecl())
801 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000802 }
803
John McCall9f54ad42009-12-10 09:41:52 +0000804 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
805 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000806 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000807
Douglas Gregora735b202009-10-13 14:39:41 +0000808 // If the original function was part of a friend declaration,
809 // inherit its namespace state and add it to the owner.
810 NamedDecl *FromFriendD
811 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
812 if (FromFriendD->getFriendObjectKind()) {
813 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000814 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000815 if (TemplateParams) {
816 ToFriendD = cast<NamedDecl>(FunctionTemplate);
817 PrevDecl = FunctionTemplate->getPreviousDeclaration();
818 } else {
819 ToFriendD = Function;
820 PrevDecl = Function->getPreviousDeclaration();
821 }
822 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
823 if (!Owner->isDependentContext() && !PrevDecl)
824 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
825
826 if (!TemplateParams)
827 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
828 }
829
Douglas Gregore53060f2009-06-25 22:08:12 +0000830 return Function;
831}
832
Douglas Gregord60e1052009-08-27 16:57:43 +0000833Decl *
834TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
835 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000836 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
837 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000838 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000839 // We are creating a function template specialization from a function
840 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000841 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000842 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000843 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000844 TemplateArgs.getInnermost().getFlatArgumentList(),
845 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000846 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
848 FunctionTemplateSpecializationInfo *Info
849 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000850 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregor6b906862009-08-21 00:16:32 +0000852 // If we already have a function template specialization, return it.
853 if (Info)
854 return Info->Function;
855 }
856
Douglas Gregor79c22782010-01-16 20:21:20 +0000857 bool MergeWithParentScope = (TemplateParams != 0) ||
858 !(isa<Decl>(Owner) &&
859 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
860 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000861
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000862 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000863 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000864 if (T.isNull())
865 return 0;
866
867 // Build the instantiated method declaration.
868 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000869 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregordec06662009-08-21 18:42:58 +0000871 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000872 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000873 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
874 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
875 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000876 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
877 Constructor->getLocation(),
878 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000879 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000880 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000881 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000882 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
883 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
884 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
885 SemaRef.Context.getCanonicalType(ClassTy));
886 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
887 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000888 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000889 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000890 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000891 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000892 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000893 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
894 ConvTy);
895 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
896 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000897 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000898 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000899 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000900 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000901 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000902 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000903 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000904 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000905
Douglas Gregord60e1052009-08-27 16:57:43 +0000906 if (TemplateParams) {
907 // Our resulting instantiation is actually a function template, since we
908 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000909 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000910 // template<typename T>
911 // struct X {
912 // template<typename U> void f(T, U);
913 // };
914 //
915 // X<int> x;
916 //
917 // We are instantiating the member template "f" within X<int>, which means
918 // substituting int for T, but leaving "f" as a member function template.
919 // Build the function template itself.
920 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
921 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000922 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000923 TemplateParams, Method);
924 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000925 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000926 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000927 } else if (FunctionTemplate) {
928 // Record this function template specialization.
929 Method->setFunctionTemplateSpecialization(SemaRef.Context,
930 FunctionTemplate,
931 &TemplateArgs.getInnermost(),
932 InsertPos);
933 } else {
934 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000935 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000936 }
937
Mike Stump1eb44332009-09-09 15:08:12 +0000938 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000939 // out-of-line, the instantiation will have the same lexical
940 // context (which will be a namespace scope) as the template.
941 if (D->isOutOfLine())
942 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregor5545e162009-03-24 00:38:23 +0000944 // Attach the parameters
945 for (unsigned P = 0; P < Params.size(); ++P)
946 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000947 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000948
949 if (InitMethodInstantiation(Method, D))
950 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000951
John McCall68263142009-11-18 22:49:29 +0000952 LookupResult Previous(SemaRef, Name, SourceLocation(),
953 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Douglas Gregord60e1052009-08-27 16:57:43 +0000955 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000956 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregordec06662009-08-21 18:42:58 +0000958 // In C++, the previous declaration we find might be a tag type
959 // (class or enum). In this case, the new declaration will hide the
960 // tag type. Note that this does does not apply if we're declaring a
961 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000962 if (Previous.isSingleTagDecl())
963 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000964 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000965
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000966 bool Redeclaration = false;
967 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000968 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000969 /*FIXME:*/OverloadableAttrRequired);
970
Douglas Gregor4ba31362009-12-01 17:24:26 +0000971 if (D->isPure())
972 SemaRef.CheckPureMethod(Method, SourceRange());
973
John McCall46460a62010-01-20 21:53:11 +0000974 Method->setAccess(D->getAccess());
975
John McCall68263142009-11-18 22:49:29 +0000976 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000977 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000978 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000980 return Method;
981}
982
Douglas Gregor615c5d42009-03-24 16:43:20 +0000983Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000984 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000985}
986
Douglas Gregor03b2b072009-03-24 00:15:49 +0000987Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000988 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000989}
990
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000991Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000992 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000993}
994
Douglas Gregor6477b692009-03-25 15:04:13 +0000995ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000996 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000997 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000998 if (DI) {
999 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1000 D->getDeclName());
1001 if (DI) T = DI->getType();
1002 } else {
1003 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1004 D->getDeclName());
1005 DI = 0;
1006 }
1007
1008 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001009 return 0;
1010
John McCall58e46772009-10-23 21:48:59 +00001011 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001012
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001013 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001014 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001015 = ParmVarDecl::Create(SemaRef.Context,
1016 SemaRef.Context.getTranslationUnitDecl(),
1017 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001018 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001019
Anders Carlsson9351c172009-08-25 03:18:48 +00001020 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001021 if (D->hasUninstantiatedDefaultArg())
1022 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001023 else if (Expr *Arg = D->getDefaultArg())
1024 Param->setUninstantiatedDefaultArg(Arg);
1025
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001026 // Note: we don't try to instantiate function parameters until after
1027 // we've instantiated the function's type. Therefore, we don't have
1028 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001029 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001030 return Param;
1031}
1032
John McCalle29ba202009-08-20 01:44:21 +00001033Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1034 TemplateTypeParmDecl *D) {
1035 // TODO: don't always clone when decls are refcounted.
1036 const Type* T = D->getTypeForDecl();
1037 assert(T->isTemplateTypeParmType());
1038 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001039
John McCalle29ba202009-08-20 01:44:21 +00001040 TemplateTypeParmDecl *Inst =
1041 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001042 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001043 TTPT->getName(),
1044 D->wasDeclaredWithTypename(),
1045 D->isParameterPack());
1046
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001047 if (D->hasDefaultArgument())
1048 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001049
Douglas Gregor550d9b22009-10-31 17:21:17 +00001050 // Introduce this template parameter's instantiation into the instantiation
1051 // scope.
1052 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1053
John McCalle29ba202009-08-20 01:44:21 +00001054 return Inst;
1055}
1056
Douglas Gregor33642df2009-10-23 23:25:44 +00001057Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1058 NonTypeTemplateParmDecl *D) {
1059 // Substitute into the type of the non-type template parameter.
1060 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001061 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001062 if (DI) {
1063 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1064 D->getDeclName());
1065 if (DI) T = DI->getType();
1066 } else {
1067 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1068 D->getDeclName());
1069 DI = 0;
1070 }
1071 if (T.isNull())
1072 return 0;
1073
1074 // Check that this type is acceptable for a non-type template parameter.
1075 bool Invalid = false;
1076 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1077 if (T.isNull()) {
1078 T = SemaRef.Context.IntTy;
1079 Invalid = true;
1080 }
1081
1082 NonTypeTemplateParmDecl *Param
1083 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1084 D->getDepth() - 1, D->getPosition(),
1085 D->getIdentifier(), T, DI);
1086 if (Invalid)
1087 Param->setInvalidDecl();
1088
1089 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001090
1091 // Introduce this template parameter's instantiation into the instantiation
1092 // scope.
1093 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001094 return Param;
1095}
1096
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001097Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001098TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1099 TemplateTemplateParmDecl *D) {
1100 // Instantiate the template parameter list of the template template parameter.
1101 TemplateParameterList *TempParams = D->getTemplateParameters();
1102 TemplateParameterList *InstParams;
1103 {
1104 // Perform the actual substitution of template parameters within a new,
1105 // local instantiation scope.
1106 Sema::LocalInstantiationScope Scope(SemaRef);
1107 InstParams = SubstTemplateParams(TempParams);
1108 if (!InstParams)
1109 return NULL;
1110 }
1111
1112 // Build the template template parameter.
1113 TemplateTemplateParmDecl *Param
1114 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1115 D->getDepth() - 1, D->getPosition(),
1116 D->getIdentifier(), InstParams);
1117 Param->setDefaultArgument(D->getDefaultArgument());
1118
1119 // Introduce this template parameter's instantiation into the instantiation
1120 // scope.
1121 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1122
1123 return Param;
1124}
1125
Douglas Gregor48c32a72009-11-17 06:07:40 +00001126Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1127 // Using directives are never dependent, so they require no explicit
1128
1129 UsingDirectiveDecl *Inst
1130 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1131 D->getNamespaceKeyLocation(),
1132 D->getQualifierRange(), D->getQualifier(),
1133 D->getIdentLocation(),
1134 D->getNominatedNamespace(),
1135 D->getCommonAncestor());
1136 Owner->addDecl(Inst);
1137 return Inst;
1138}
1139
John McCalled976492009-12-04 22:46:56 +00001140Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1141 // The nested name specifier is non-dependent, so no transformation
1142 // is required.
1143
John McCall9f54ad42009-12-10 09:41:52 +00001144 // We only need to do redeclaration lookups if we're in a class
1145 // scope (in fact, it's not really even possible in non-class
1146 // scopes).
1147 bool CheckRedeclaration = Owner->isRecord();
1148
1149 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1150 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1151
John McCalled976492009-12-04 22:46:56 +00001152 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1153 D->getLocation(),
1154 D->getNestedNameRange(),
1155 D->getUsingLocation(),
1156 D->getTargetNestedNameDecl(),
1157 D->getDeclName(),
1158 D->isTypeName());
1159
1160 CXXScopeSpec SS;
1161 SS.setScopeRep(D->getTargetNestedNameDecl());
1162 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001163
1164 if (CheckRedeclaration) {
1165 Prev.setHideTags(false);
1166 SemaRef.LookupQualifiedName(Prev, Owner);
1167
1168 // Check for invalid redeclarations.
1169 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1170 D->isTypeName(), SS,
1171 D->getLocation(), Prev))
1172 NewUD->setInvalidDecl();
1173
1174 }
1175
1176 if (!NewUD->isInvalidDecl() &&
1177 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001178 D->getLocation()))
1179 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001180
John McCalled976492009-12-04 22:46:56 +00001181 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1182 NewUD->setAccess(D->getAccess());
1183 Owner->addDecl(NewUD);
1184
John McCall9f54ad42009-12-10 09:41:52 +00001185 // Don't process the shadow decls for an invalid decl.
1186 if (NewUD->isInvalidDecl())
1187 return NewUD;
1188
John McCall323c3102009-12-22 22:26:37 +00001189 bool isFunctionScope = Owner->isFunctionOrMethod();
1190
John McCall9f54ad42009-12-10 09:41:52 +00001191 // Process the shadow decls.
1192 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1193 I != E; ++I) {
1194 UsingShadowDecl *Shadow = *I;
1195 NamedDecl *InstTarget =
1196 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1197 TemplateArgs));
1198
1199 if (CheckRedeclaration &&
1200 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1201 continue;
1202
1203 UsingShadowDecl *InstShadow
1204 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1205 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001206
1207 if (isFunctionScope)
1208 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001209 }
John McCalled976492009-12-04 22:46:56 +00001210
1211 return NewUD;
1212}
1213
1214Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001215 // Ignore these; we handle them in bulk when processing the UsingDecl.
1216 return 0;
John McCalled976492009-12-04 22:46:56 +00001217}
1218
John McCall7ba107a2009-11-18 02:36:19 +00001219Decl * TemplateDeclInstantiator
1220 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 NestedNameSpecifier *NNS =
1222 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1223 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001224 TemplateArgs);
1225 if (!NNS)
1226 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001228 CXXScopeSpec SS;
1229 SS.setRange(D->getTargetNestedNameRange());
1230 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
1232 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001233 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001234 D->getUsingLoc(), SS, D->getLocation(),
1235 D->getDeclName(), 0,
1236 /*instantiation*/ true,
1237 /*typename*/ true, D->getTypenameLoc());
1238 if (UD)
John McCalled976492009-12-04 22:46:56 +00001239 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1240
John McCall7ba107a2009-11-18 02:36:19 +00001241 return UD;
1242}
1243
1244Decl * TemplateDeclInstantiator
1245 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1246 NestedNameSpecifier *NNS =
1247 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1248 D->getTargetNestedNameRange(),
1249 TemplateArgs);
1250 if (!NNS)
1251 return 0;
1252
1253 CXXScopeSpec SS;
1254 SS.setRange(D->getTargetNestedNameRange());
1255 SS.setScopeRep(NNS);
1256
1257 NamedDecl *UD =
1258 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1259 D->getUsingLoc(), SS, D->getLocation(),
1260 D->getDeclName(), 0,
1261 /*instantiation*/ true,
1262 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001263 if (UD)
John McCalled976492009-12-04 22:46:56 +00001264 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1265
Anders Carlsson0d8df782009-08-29 19:37:28 +00001266 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001267}
1268
John McCallce3ff2b2009-08-25 22:02:44 +00001269Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001270 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001271 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001272 return Instantiator.Visit(D);
1273}
1274
John McCalle29ba202009-08-20 01:44:21 +00001275/// \brief Instantiates a nested template parameter list in the current
1276/// instantiation context.
1277///
1278/// \param L The parameter list to instantiate
1279///
1280/// \returns NULL if there was an error
1281TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001282TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001283 // Get errors for all the parameters before bailing out.
1284 bool Invalid = false;
1285
1286 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001287 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001288 ParamVector Params;
1289 Params.reserve(N);
1290 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1291 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001292 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001293 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001294 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001295 }
1296
1297 // Clean up if we had an error.
1298 if (Invalid) {
1299 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1300 PI != PE; ++PI)
1301 if (*PI)
1302 (*PI)->Destroy(SemaRef.Context);
1303 return NULL;
1304 }
1305
1306 TemplateParameterList *InstL
1307 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1308 L->getLAngleLoc(), &Params.front(), N,
1309 L->getRAngleLoc());
1310 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001311}
John McCalle29ba202009-08-20 01:44:21 +00001312
Douglas Gregored9c0f92009-10-29 00:04:11 +00001313/// \brief Instantiate the declaration of a class template partial
1314/// specialization.
1315///
1316/// \param ClassTemplate the (instantiated) class template that is partially
1317// specialized by the instantiation of \p PartialSpec.
1318///
1319/// \param PartialSpec the (uninstantiated) class template partial
1320/// specialization that we are instantiating.
1321///
1322/// \returns true if there was an error, false otherwise.
1323bool
1324TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1325 ClassTemplateDecl *ClassTemplate,
1326 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001327 // Create a local instantiation scope for this class template partial
1328 // specialization, which will contain the instantiations of the template
1329 // parameters.
1330 Sema::LocalInstantiationScope Scope(SemaRef);
1331
Douglas Gregored9c0f92009-10-29 00:04:11 +00001332 // Substitute into the template parameters of the class template partial
1333 // specialization.
1334 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1335 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1336 if (!InstParams)
1337 return true;
1338
1339 // Substitute into the template arguments of the class template partial
1340 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001341 const TemplateArgumentLoc *PartialSpecTemplateArgs
1342 = PartialSpec->getTemplateArgsAsWritten();
1343 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1344
John McCalld5532b62009-11-23 01:53:49 +00001345 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001346 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001347 TemplateArgumentLoc Loc;
1348 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001349 return true;
John McCalld5532b62009-11-23 01:53:49 +00001350 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001351 }
1352
1353
1354 // Check that the template argument list is well-formed for this
1355 // class template.
1356 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1357 InstTemplateArgs.size());
1358 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1359 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001360 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001361 false,
1362 Converted))
1363 return true;
1364
1365 // Figure out where to insert this class template partial specialization
1366 // in the member template's set of class template partial specializations.
1367 llvm::FoldingSetNodeID ID;
1368 ClassTemplatePartialSpecializationDecl::Profile(ID,
1369 Converted.getFlatArguments(),
1370 Converted.flatSize(),
1371 SemaRef.Context);
1372 void *InsertPos = 0;
1373 ClassTemplateSpecializationDecl *PrevDecl
1374 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1375 InsertPos);
1376
1377 // Build the canonical type that describes the converted template
1378 // arguments of the class template partial specialization.
1379 QualType CanonType
1380 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1381 Converted.getFlatArguments(),
1382 Converted.flatSize());
1383
1384 // Build the fully-sugared type for this class template
1385 // specialization as the user wrote in the specialization
1386 // itself. This means that we'll pretty-print the type retrieved
1387 // from the specialization's declaration the way that the user
1388 // actually wrote the specialization, rather than formatting the
1389 // name based on the "canonical" representation used to store the
1390 // template arguments in the specialization.
1391 QualType WrittenTy
1392 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001393 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001394 CanonType);
1395
1396 if (PrevDecl) {
1397 // We've already seen a partial specialization with the same template
1398 // parameters and template arguments. This can happen, for example, when
1399 // substituting the outer template arguments ends up causing two
1400 // class template partial specializations of a member class template
1401 // to have identical forms, e.g.,
1402 //
1403 // template<typename T, typename U>
1404 // struct Outer {
1405 // template<typename X, typename Y> struct Inner;
1406 // template<typename Y> struct Inner<T, Y>;
1407 // template<typename Y> struct Inner<U, Y>;
1408 // };
1409 //
1410 // Outer<int, int> outer; // error: the partial specializations of Inner
1411 // // have the same signature.
1412 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1413 << WrittenTy;
1414 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1415 << SemaRef.Context.getTypeDeclType(PrevDecl);
1416 return true;
1417 }
1418
1419
1420 // Create the class template partial specialization declaration.
1421 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1422 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1423 PartialSpec->getLocation(),
1424 InstParams,
1425 ClassTemplate,
1426 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001427 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001428 0);
1429 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1430 InstPartialSpec->setTypeAsWritten(WrittenTy);
1431
1432 // Add this partial specialization to the set of class template partial
1433 // specializations.
1434 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1435 InsertPos);
1436 return false;
1437}
1438
John McCallce3ff2b2009-08-25 22:02:44 +00001439/// \brief Does substitution on the type of the given function, including
1440/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001441///
John McCallce3ff2b2009-08-25 22:02:44 +00001442/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001443///
1444/// \param Params the instantiated parameter declarations
1445
John McCallce3ff2b2009-08-25 22:02:44 +00001446/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001447/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001448QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001449TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001450 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1451 bool InvalidDecl = false;
1452
John McCallce3ff2b2009-08-25 22:02:44 +00001453 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001454 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001455 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001456 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001457 PEnd = D->param_end();
1458 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001459 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001460 if (PInst->getType()->isVoidType()) {
1461 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1462 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001463 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001464 PInst->getType(),
1465 diag::err_abstract_type_in_decl,
1466 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001467 PInst->setInvalidDecl();
1468
1469 Params.push_back(PInst);
1470 ParamTys.push_back(PInst->getType());
1471
1472 if (PInst->isInvalidDecl())
1473 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001474 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001475 InvalidDecl = true;
1476 }
1477
1478 // FIXME: Deallocate dead declarations.
1479 if (InvalidDecl)
1480 return QualType();
1481
John McCall183700f2009-09-21 23:43:11 +00001482 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001483 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001484 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001485 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1486 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001487 if (ResultType.isNull())
1488 return QualType();
1489
Jay Foadbeaaccd2009-05-21 09:52:38 +00001490 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001491 Proto->isVariadic(), Proto->getTypeQuals(),
1492 D->getLocation(), D->getDeclName());
1493}
1494
Mike Stump1eb44332009-09-09 15:08:12 +00001495/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001496/// declaration (New) from the corresponding fields of its template (Tmpl).
1497///
1498/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001499bool
1500TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001501 FunctionDecl *Tmpl) {
1502 if (Tmpl->isDeleted())
1503 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Douglas Gregorcca9e962009-07-01 22:01:06 +00001505 // If we are performing substituting explicitly-specified template arguments
1506 // or deduced template arguments into a function template and we reach this
1507 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001508 // to keeping the new function template specialization. We therefore
1509 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001510 // into a template instantiation for this specific function template
1511 // specialization, which is not a SFINAE context, so that we diagnose any
1512 // further errors in the declaration itself.
1513 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1514 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1515 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1516 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001517 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001518 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001519 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001520 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001521 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001522 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1523 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001524 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001525 }
1526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001528 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1529 assert(Proto && "Function template without prototype?");
1530
1531 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1532 Proto->getNoReturnAttr()) {
1533 // The function has an exception specification or a "noreturn"
1534 // attribute. Substitute into each of the exception types.
1535 llvm::SmallVector<QualType, 4> Exceptions;
1536 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1537 // FIXME: Poor location information!
1538 QualType T
1539 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1540 New->getLocation(), New->getDeclName());
1541 if (T.isNull() ||
1542 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1543 continue;
1544
1545 Exceptions.push_back(T);
1546 }
1547
1548 // Rebuild the function type
1549
1550 const FunctionProtoType *NewProto
1551 = New->getType()->getAs<FunctionProtoType>();
1552 assert(NewProto && "Template instantiation without function prototype?");
1553 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1554 NewProto->arg_type_begin(),
1555 NewProto->getNumArgs(),
1556 NewProto->isVariadic(),
1557 NewProto->getTypeQuals(),
1558 Proto->hasExceptionSpec(),
1559 Proto->hasAnyExceptionSpec(),
1560 Exceptions.size(),
1561 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001562 Proto->getNoReturnAttr(),
1563 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001564 }
1565
Douglas Gregore53060f2009-06-25 22:08:12 +00001566 return false;
1567}
1568
Douglas Gregor5545e162009-03-24 00:38:23 +00001569/// \brief Initializes common fields of an instantiated method
1570/// declaration (New) from the corresponding fields of its template
1571/// (Tmpl).
1572///
1573/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001574bool
1575TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001576 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001577 if (InitFunctionInstantiation(New, Tmpl))
1578 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Douglas Gregor5545e162009-03-24 00:38:23 +00001580 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1581 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001582 if (Tmpl->isVirtualAsWritten())
1583 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001584
1585 // FIXME: attributes
1586 // FIXME: New needs a pointer to Tmpl
1587 return false;
1588}
Douglas Gregora58861f2009-05-13 20:28:22 +00001589
1590/// \brief Instantiate the definition of the given function from its
1591/// template.
1592///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001593/// \param PointOfInstantiation the point at which the instantiation was
1594/// required. Note that this is not precisely a "point of instantiation"
1595/// for the function, but it's close.
1596///
Douglas Gregora58861f2009-05-13 20:28:22 +00001597/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001598/// function template specialization or member function of a class template
1599/// specialization.
1600///
1601/// \param Recursive if true, recursively instantiates any functions that
1602/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001603///
1604/// \param DefinitionRequired if true, then we are performing an explicit
1605/// instantiation where the body of the function is required. Complain if
1606/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001607void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001608 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001609 bool Recursive,
1610 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001611 if (Function->isInvalidDecl())
1612 return;
1613
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001614 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001616 // Never instantiate an explicit specialization.
1617 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1618 return;
1619
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001620 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001621 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001622 Stmt *Pattern = 0;
1623 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001624 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001625
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001626 if (!Pattern) {
1627 if (DefinitionRequired) {
1628 if (Function->getPrimaryTemplate())
1629 Diag(PointOfInstantiation,
1630 diag::err_explicit_instantiation_undefined_func_template)
1631 << Function->getPrimaryTemplate();
1632 else
1633 Diag(PointOfInstantiation,
1634 diag::err_explicit_instantiation_undefined_member)
1635 << 1 << Function->getDeclName() << Function->getDeclContext();
1636
1637 if (PatternDecl)
1638 Diag(PatternDecl->getLocation(),
1639 diag::note_explicit_instantiation_here);
1640 }
1641
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001642 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001643 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001644
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001645 // C++0x [temp.explicit]p9:
1646 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001647 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001648 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001649 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001650 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001651 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001652 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001654 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1655 if (Inst)
1656 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001657
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001658 // If we're performing recursive template instantiation, create our own
1659 // queue of pending implicit instantiations that we will instantiate later,
1660 // while we're still within our own instantiation context.
1661 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1662 if (Recursive)
1663 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001665 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1666
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001667 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001668 // recorded, unless we're actually a member function within a local
1669 // class, in which case we need to merge our results with the parent
1670 // scope (of the enclosing function).
1671 bool MergeWithParentScope = false;
1672 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1673 MergeWithParentScope = Rec->isLocalClass();
1674
1675 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001677 // Introduce the instantiated function parameters into the local
1678 // instantiation scope.
1679 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1680 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1681 Function->getParamDecl(I));
1682
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001683 // Enter the scope of this instantiation. We don't use
1684 // PushDeclContext because we don't have a scope.
1685 DeclContext *PreviousContext = CurContext;
1686 CurContext = Function;
1687
Mike Stump1eb44332009-09-09 15:08:12 +00001688 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001689 getTemplateInstantiationArgs(Function);
1690
1691 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001692 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001693 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1694 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1695 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001696 }
1697
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001698 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001699 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001700
Douglas Gregor52604ab2009-09-11 21:19:12 +00001701 if (Body.isInvalid())
1702 Function->setInvalidDecl();
1703
Mike Stump1eb44332009-09-09 15:08:12 +00001704 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001705 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001706
1707 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001708
1709 DeclGroupRef DG(Function);
1710 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Douglas Gregor60406be2010-01-16 22:29:39 +00001712 // This class may have local implicit instantiations that need to be
1713 // instantiation within this scope.
1714 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1715 Scope.Exit();
1716
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001717 if (Recursive) {
1718 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001719 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001720 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001722 // Restore the set of pending implicit instantiations.
1723 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1724 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001725}
1726
1727/// \brief Instantiate the definition of the given variable from its
1728/// template.
1729///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001730/// \param PointOfInstantiation the point at which the instantiation was
1731/// required. Note that this is not precisely a "point of instantiation"
1732/// for the function, but it's close.
1733///
1734/// \param Var the already-instantiated declaration of a static member
1735/// variable of a class template specialization.
1736///
1737/// \param Recursive if true, recursively instantiates any functions that
1738/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001739///
1740/// \param DefinitionRequired if true, then we are performing an explicit
1741/// instantiation where an out-of-line definition of the member variable
1742/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001743void Sema::InstantiateStaticDataMemberDefinition(
1744 SourceLocation PointOfInstantiation,
1745 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001746 bool Recursive,
1747 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001748 if (Var->isInvalidDecl())
1749 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Douglas Gregor7caa6822009-07-24 20:34:43 +00001751 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001752 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001753 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001754 assert(Def->isStaticDataMember() && "Not a static data member?");
1755 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregor0d035142009-10-27 18:42:08 +00001757 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001758 // We did not find an out-of-line definition of this static data member,
1759 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001760 // instantiate this definition (or provide a specialization for it) in
1761 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001762 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001763 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001764 Diag(PointOfInstantiation,
1765 diag::err_explicit_instantiation_undefined_member)
1766 << 2 << Var->getDeclName() << Var->getDeclContext();
1767 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1768 }
1769
Douglas Gregor7caa6822009-07-24 20:34:43 +00001770 return;
1771 }
1772
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001773 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001774 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001775 return;
1776
1777 // C++0x [temp.explicit]p9:
1778 // Except for inline functions, other explicit instantiation declarations
1779 // have the effect of suppressing the implicit instantiation of the entity
1780 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001781 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001782 == TSK_ExplicitInstantiationDeclaration)
1783 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Douglas Gregor7caa6822009-07-24 20:34:43 +00001785 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1786 if (Inst)
1787 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Douglas Gregor7caa6822009-07-24 20:34:43 +00001789 // If we're performing recursive template instantiation, create our own
1790 // queue of pending implicit instantiations that we will instantiate later,
1791 // while we're still within our own instantiation context.
1792 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1793 if (Recursive)
1794 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregor7caa6822009-07-24 20:34:43 +00001796 // Enter the scope of this instantiation. We don't use
1797 // PushDeclContext because we don't have a scope.
1798 DeclContext *PreviousContext = CurContext;
1799 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001801 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001802 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001803 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001804 CurContext = PreviousContext;
1805
1806 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001807 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001808 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1809 assert(MSInfo && "Missing member specialization information?");
1810 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1811 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001812 DeclGroupRef DG(Var);
1813 Consumer.HandleTopLevelDecl(DG);
1814 }
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Douglas Gregor7caa6822009-07-24 20:34:43 +00001816 if (Recursive) {
1817 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001818 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001819 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Douglas Gregor7caa6822009-07-24 20:34:43 +00001821 // Restore the set of pending implicit instantiations.
1822 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001823 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001824}
Douglas Gregor815215d2009-05-27 05:35:12 +00001825
Anders Carlsson09025312009-08-29 05:16:22 +00001826void
1827Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1828 const CXXConstructorDecl *Tmpl,
1829 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Anders Carlsson09025312009-08-29 05:16:22 +00001831 llvm::SmallVector<MemInitTy*, 4> NewInits;
1832
1833 // Instantiate all the initializers.
1834 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001835 InitsEnd = Tmpl->init_end();
1836 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001837 CXXBaseOrMemberInitializer *Init = *Inits;
1838
1839 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Anders Carlsson09025312009-08-29 05:16:22 +00001841 // Instantiate all the arguments.
1842 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1843 Args != ArgsEnd; ++Args) {
1844 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1845
1846 if (NewArg.isInvalid())
1847 New->setInvalidDecl();
1848 else
1849 NewArgs.push_back(NewArg.takeAs<Expr>());
1850 }
1851
1852 MemInitResult NewInit;
1853
1854 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001855 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001856 TemplateArgs,
1857 Init->getSourceLocation(),
1858 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001859 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001860 New->setInvalidDecl();
1861 continue;
1862 }
1863
John McCalla93c9342009-12-07 02:54:59 +00001864 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001865 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001866 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001867 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001868 Init->getRParenLoc(),
1869 New->getParent());
1870 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001871 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001873 // Is this an anonymous union?
1874 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001875 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001876 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001877 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1878 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001879
1880 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001881 NewArgs.size(),
1882 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001883 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001884 Init->getRParenLoc());
1885 }
1886
1887 if (NewInit.isInvalid())
1888 New->setInvalidDecl();
1889 else {
1890 // FIXME: It would be nice if ASTOwningVector had a release function.
1891 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Anders Carlsson09025312009-08-29 05:16:22 +00001893 NewInits.push_back((MemInitTy *)NewInit.get());
1894 }
1895 }
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Anders Carlsson09025312009-08-29 05:16:22 +00001897 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001898 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001899 /*FIXME: ColonLoc */
1900 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001901 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001902}
1903
John McCall52a575a2009-08-29 08:11:13 +00001904// TODO: this could be templated if the various decl types used the
1905// same method name.
1906static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1907 ClassTemplateDecl *Instance) {
1908 Pattern = Pattern->getCanonicalDecl();
1909
1910 do {
1911 Instance = Instance->getCanonicalDecl();
1912 if (Pattern == Instance) return true;
1913 Instance = Instance->getInstantiatedFromMemberTemplate();
1914 } while (Instance);
1915
1916 return false;
1917}
1918
Douglas Gregor0d696532009-09-28 06:34:35 +00001919static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1920 FunctionTemplateDecl *Instance) {
1921 Pattern = Pattern->getCanonicalDecl();
1922
1923 do {
1924 Instance = Instance->getCanonicalDecl();
1925 if (Pattern == Instance) return true;
1926 Instance = Instance->getInstantiatedFromMemberTemplate();
1927 } while (Instance);
1928
1929 return false;
1930}
1931
Douglas Gregored9c0f92009-10-29 00:04:11 +00001932static bool
1933isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1934 ClassTemplatePartialSpecializationDecl *Instance) {
1935 Pattern
1936 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1937 do {
1938 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1939 Instance->getCanonicalDecl());
1940 if (Pattern == Instance)
1941 return true;
1942 Instance = Instance->getInstantiatedFromMember();
1943 } while (Instance);
1944
1945 return false;
1946}
1947
John McCall52a575a2009-08-29 08:11:13 +00001948static bool isInstantiationOf(CXXRecordDecl *Pattern,
1949 CXXRecordDecl *Instance) {
1950 Pattern = Pattern->getCanonicalDecl();
1951
1952 do {
1953 Instance = Instance->getCanonicalDecl();
1954 if (Pattern == Instance) return true;
1955 Instance = Instance->getInstantiatedFromMemberClass();
1956 } while (Instance);
1957
1958 return false;
1959}
1960
1961static bool isInstantiationOf(FunctionDecl *Pattern,
1962 FunctionDecl *Instance) {
1963 Pattern = Pattern->getCanonicalDecl();
1964
1965 do {
1966 Instance = Instance->getCanonicalDecl();
1967 if (Pattern == Instance) return true;
1968 Instance = Instance->getInstantiatedFromMemberFunction();
1969 } while (Instance);
1970
1971 return false;
1972}
1973
1974static bool isInstantiationOf(EnumDecl *Pattern,
1975 EnumDecl *Instance) {
1976 Pattern = Pattern->getCanonicalDecl();
1977
1978 do {
1979 Instance = Instance->getCanonicalDecl();
1980 if (Pattern == Instance) return true;
1981 Instance = Instance->getInstantiatedFromMemberEnum();
1982 } while (Instance);
1983
1984 return false;
1985}
1986
John McCalled976492009-12-04 22:46:56 +00001987static bool isInstantiationOf(UsingShadowDecl *Pattern,
1988 UsingShadowDecl *Instance,
1989 ASTContext &C) {
1990 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1991}
1992
1993static bool isInstantiationOf(UsingDecl *Pattern,
1994 UsingDecl *Instance,
1995 ASTContext &C) {
1996 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1997}
1998
John McCall7ba107a2009-11-18 02:36:19 +00001999static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2000 UsingDecl *Instance,
2001 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002002 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002003}
2004
2005static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002006 UsingDecl *Instance,
2007 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002008 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002009}
2010
John McCall52a575a2009-08-29 08:11:13 +00002011static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2012 VarDecl *Instance) {
2013 assert(Instance->isStaticDataMember());
2014
2015 Pattern = Pattern->getCanonicalDecl();
2016
2017 do {
2018 Instance = Instance->getCanonicalDecl();
2019 if (Pattern == Instance) return true;
2020 Instance = Instance->getInstantiatedFromStaticDataMember();
2021 } while (Instance);
2022
2023 return false;
2024}
2025
John McCalled976492009-12-04 22:46:56 +00002026// Other is the prospective instantiation
2027// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002028static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002029 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002030 if (UnresolvedUsingTypenameDecl *UUD
2031 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2032 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2033 return isInstantiationOf(UUD, UD, Ctx);
2034 }
2035 }
2036
2037 if (UnresolvedUsingValueDecl *UUD
2038 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002039 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2040 return isInstantiationOf(UUD, UD, Ctx);
2041 }
2042 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002043
Anders Carlsson0d8df782009-08-29 19:37:28 +00002044 return false;
2045 }
Mike Stump1eb44332009-09-09 15:08:12 +00002046
John McCall52a575a2009-08-29 08:11:13 +00002047 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2048 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
John McCall52a575a2009-08-29 08:11:13 +00002050 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2051 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002052
John McCall52a575a2009-08-29 08:11:13 +00002053 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2054 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002055
Douglas Gregor7caa6822009-07-24 20:34:43 +00002056 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002057 if (Var->isStaticDataMember())
2058 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2059
2060 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2061 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002062
Douglas Gregor0d696532009-09-28 06:34:35 +00002063 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2064 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2065
Douglas Gregored9c0f92009-10-29 00:04:11 +00002066 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2067 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2068 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2069 PartialSpec);
2070
Anders Carlssond8b285f2009-09-01 04:26:58 +00002071 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2072 if (!Field->getDeclName()) {
2073 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002074 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002075 cast<FieldDecl>(D);
2076 }
2077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
John McCalled976492009-12-04 22:46:56 +00002079 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2080 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2081
2082 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2083 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2084
Douglas Gregor815215d2009-05-27 05:35:12 +00002085 return D->getDeclName() && isa<NamedDecl>(Other) &&
2086 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2087}
2088
2089template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002090static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002091 NamedDecl *D,
2092 ForwardIterator first,
2093 ForwardIterator last) {
2094 for (; first != last; ++first)
2095 if (isInstantiationOf(Ctx, D, *first))
2096 return cast<NamedDecl>(*first);
2097
2098 return 0;
2099}
2100
John McCall02cace72009-08-28 07:59:38 +00002101/// \brief Finds the instantiation of the given declaration context
2102/// within the current instantiation.
2103///
2104/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002105DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2106 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002107 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002108 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002109 return cast_or_null<DeclContext>(ID);
2110 } else return DC;
2111}
2112
Douglas Gregored961e72009-05-27 17:54:46 +00002113/// \brief Find the instantiation of the given declaration within the
2114/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002115///
2116/// This routine is intended to be used when \p D is a declaration
2117/// referenced from within a template, that needs to mapped into the
2118/// corresponding declaration within an instantiation. For example,
2119/// given:
2120///
2121/// \code
2122/// template<typename T>
2123/// struct X {
2124/// enum Kind {
2125/// KnownValue = sizeof(T)
2126/// };
2127///
2128/// bool getKind() const { return KnownValue; }
2129/// };
2130///
2131/// template struct X<int>;
2132/// \endcode
2133///
2134/// In the instantiation of X<int>::getKind(), we need to map the
2135/// EnumConstantDecl for KnownValue (which refers to
2136/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002137/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2138/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002139NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2140 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002141 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002142 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2143 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2144 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002145 // D is a local of some kind. Look into the map of local
2146 // declarations to their instantiations.
2147 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2148 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002149
Douglas Gregore95b4092009-09-16 18:34:49 +00002150 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2151 if (!Record->isDependentContext())
2152 return D;
2153
2154 // If the RecordDecl is actually the injected-class-name or a "templated"
2155 // declaration for a class template or class template partial
2156 // specialization, substitute into the injected-class-name of the
2157 // class template or partial specialization to find the new DeclContext.
2158 QualType T;
2159 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2160
2161 if (ClassTemplate) {
2162 T = ClassTemplate->getInjectedClassNameType(Context);
2163 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2164 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2165 T = Context.getTypeDeclType(Record);
2166 ClassTemplate = PartialSpec->getSpecializedTemplate();
2167 }
2168
2169 if (!T.isNull()) {
2170 // Substitute into the injected-class-name to get the type corresponding
2171 // to the instantiation we want. This substitution should never fail,
2172 // since we know we can instantiate the injected-class-name or we wouldn't
2173 // have gotten to the injected-class-name!
2174 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2175 // instantiation in the common case?
2176 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2177 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2178
2179 if (!T->isDependentType()) {
2180 assert(T->isRecordType() && "Instantiation must produce a record type");
2181 return T->getAs<RecordType>()->getDecl();
2182 }
2183
2184 // We are performing "partial" template instantiation to create the
2185 // member declarations for the members of a class template
2186 // specialization. Therefore, D is actually referring to something in
2187 // the current instantiation. Look through the current context,
2188 // which contains actual instantiations, to find the instantiation of
2189 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002190 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002191 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002192 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002193 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002194 if (isInstantiationOf(ClassTemplate,
2195 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002196 return Spec;
2197 }
2198
Mike Stump1eb44332009-09-09 15:08:12 +00002199 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002200 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002201 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002202 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002203
2204 // Fall through to deal with other dependent record types (e.g.,
2205 // anonymous unions in class templates).
2206 }
John McCall52a575a2009-08-29 08:11:13 +00002207
Douglas Gregore95b4092009-09-16 18:34:49 +00002208 if (!ParentDC->isDependentContext())
2209 return D;
2210
2211 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002212 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002213 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor815215d2009-05-27 05:35:12 +00002215 if (ParentDC != D->getDeclContext()) {
2216 // We performed some kind of instantiation in the parent context,
2217 // so now we need to look into the instantiated parent context to
2218 // find the instantiation of the declaration D.
2219 NamedDecl *Result = 0;
2220 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002221 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002222 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2223 } else {
2224 // Since we don't have a name for the entity we're looking for,
2225 // our only option is to walk through all of the declarations to
2226 // find that name. This will occur in a few cases:
2227 //
2228 // - anonymous struct/union within a template
2229 // - unnamed class/struct/union/enum within a template
2230 //
2231 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002232 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002233 ParentDC->decls_begin(),
2234 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002235 }
Mike Stump1eb44332009-09-09 15:08:12 +00002236
John McCall9f54ad42009-12-10 09:41:52 +00002237 // UsingShadowDecls can instantiate to nothing because of using hiding.
2238 assert((Result || isa<UsingShadowDecl>(D))
2239 && "Unable to find instantiation of declaration!");
2240
Douglas Gregor815215d2009-05-27 05:35:12 +00002241 D = Result;
2242 }
2243
Douglas Gregor815215d2009-05-27 05:35:12 +00002244 return D;
2245}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002246
Mike Stump1eb44332009-09-09 15:08:12 +00002247/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002248/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002249void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2250 while (!PendingLocalImplicitInstantiations.empty() ||
2251 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2252 PendingImplicitInstantiation Inst;
2253
2254 if (PendingLocalImplicitInstantiations.empty()) {
2255 Inst = PendingImplicitInstantiations.front();
2256 PendingImplicitInstantiations.pop_front();
2257 } else {
2258 Inst = PendingLocalImplicitInstantiations.front();
2259 PendingLocalImplicitInstantiations.pop_front();
2260 }
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Douglas Gregor7caa6822009-07-24 20:34:43 +00002262 // Instantiate function definitions
2263 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002264 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002265 Function->getLocation(), *this,
2266 Context.getSourceManager(),
2267 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002269 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002270 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002271 continue;
2272 }
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Douglas Gregor7caa6822009-07-24 20:34:43 +00002274 // Instantiate static data member definitions.
2275 VarDecl *Var = cast<VarDecl>(Inst.first);
2276 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002277
Mike Stump1eb44332009-09-09 15:08:12 +00002278 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002279 Var->getLocation(), *this,
2280 Context.getSourceManager(),
2281 "instantiating static data member "
2282 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Douglas Gregor7caa6822009-07-24 20:34:43 +00002284 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002285 }
2286}