blob: d526962323d118f34d7e8a6fafeb01a15606cb74 [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) {
John McCall3b85ecf2010-01-23 22:37:59 +0000496 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000497 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000498 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000499 LastEnumConst = EnumConst;
500 }
501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000503 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000504 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000505 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
506 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000507 &Enumerators[0], Enumerators.size(),
508 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000509
510 return Enum;
511}
512
Douglas Gregor6477b692009-03-25 15:04:13 +0000513Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
514 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
515 return 0;
516}
517
Douglas Gregored9c0f92009-10-29 00:04:11 +0000518namespace {
519 class SortDeclByLocation {
520 SourceManager &SourceMgr;
521
522 public:
523 explicit SortDeclByLocation(SourceManager &SourceMgr)
524 : SourceMgr(SourceMgr) { }
525
526 bool operator()(const Decl *X, const Decl *Y) const {
527 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
528 Y->getLocation());
529 }
530 };
531}
532
John McCalle29ba202009-08-20 01:44:21 +0000533Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000534 // Create a local instantiation scope for this class template, which
535 // will contain the instantiations of the template parameters.
536 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000537 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000538 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000539 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000540 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000541
542 CXXRecordDecl *Pattern = D->getTemplatedDecl();
543 CXXRecordDecl *RecordInst
544 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
545 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000546 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
547 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000548
549 ClassTemplateDecl *Inst
550 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
551 D->getIdentifier(), InstParams, RecordInst, 0);
552 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000553 if (D->getFriendObjectKind())
554 Inst->setObjectOfFriendDecl(true);
555 else
556 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000557 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000558
559 // Trigger creation of the type for the instantiation.
560 SemaRef.Context.getTypeDeclType(RecordInst);
561
Douglas Gregor259571e2009-10-30 22:42:42 +0000562 // Finish handling of friends.
563 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000564 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000565 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000566
John McCall46460a62010-01-20 21:53:11 +0000567 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000568 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000569
570 // First, we sort the partial specializations by location, so
571 // that we instantiate them in the order they were declared.
572 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
573 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
574 P = D->getPartialSpecializations().begin(),
575 PEnd = D->getPartialSpecializations().end();
576 P != PEnd; ++P)
577 PartialSpecs.push_back(&*P);
578 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
579 SortDeclByLocation(SemaRef.SourceMgr));
580
581 // Instantiate all of the partial specializations of this member class
582 // template.
583 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
584 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
585
John McCalle29ba202009-08-20 01:44:21 +0000586 return Inst;
587}
588
Douglas Gregord60e1052009-08-27 16:57:43 +0000589Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000590TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
591 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000592 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
593
594 // Lookup the already-instantiated declaration in the instantiation
595 // of the class template and return that.
596 DeclContext::lookup_result Found
597 = Owner->lookup(ClassTemplate->getDeclName());
598 if (Found.first == Found.second)
599 return 0;
600
601 ClassTemplateDecl *InstClassTemplate
602 = dyn_cast<ClassTemplateDecl>(*Found.first);
603 if (!InstClassTemplate)
604 return 0;
605
606 Decl *DCanon = D->getCanonicalDecl();
607 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
608 P = InstClassTemplate->getPartialSpecializations().begin(),
609 PEnd = InstClassTemplate->getPartialSpecializations().end();
610 P != PEnd; ++P) {
611 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
612 return &*P;
613 }
614
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000615 return 0;
616}
617
618Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000619TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000620 // Create a local instantiation scope for this function template, which
621 // will contain the instantiations of the template parameters and then get
622 // merged with the local instantiation scope for the function template
623 // itself.
624 Sema::LocalInstantiationScope Scope(SemaRef);
625
Douglas Gregord60e1052009-08-27 16:57:43 +0000626 TemplateParameterList *TempParams = D->getTemplateParameters();
627 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000628 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000629 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000630
Douglas Gregora735b202009-10-13 14:39:41 +0000631 FunctionDecl *Instantiated = 0;
632 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
633 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
634 InstParams));
635 else
636 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
637 D->getTemplatedDecl(),
638 InstParams));
639
640 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000641 return 0;
642
John McCall46460a62010-01-20 21:53:11 +0000643 Instantiated->setAccess(D->getAccess());
644
Mike Stump1eb44332009-09-09 15:08:12 +0000645 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000646 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000647 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000648 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000649 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000650 assert(InstTemplate &&
651 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000652
653 // Link the instantiation back to the pattern *unless* this is a
654 // non-definition friend declaration.
655 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
656 !(InstTemplate->getFriendObjectKind() &&
657 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000658 InstTemplate->setInstantiatedFromMemberTemplate(D);
659
660 // Add non-friends into the owner.
661 if (!InstTemplate->getFriendObjectKind())
662 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000663 return InstTemplate;
664}
665
Douglas Gregord475b8d2009-03-25 21:17:03 +0000666Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
667 CXXRecordDecl *PrevDecl = 0;
668 if (D->isInjectedClassName())
669 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000670 else if (D->getPreviousDeclaration()) {
671 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
672 TemplateArgs);
673 if (!Prev) return 0;
674 PrevDecl = cast<CXXRecordDecl>(Prev);
675 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000676
677 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000678 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000679 D->getLocation(), D->getIdentifier(),
680 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000681 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000682 // FIXME: Check against AS_none is an ugly hack to work around the issue that
683 // the tag decls introduced by friend class declarations don't have an access
684 // specifier. Remove once this area of the code gets sorted out.
685 if (D->getAccess() != AS_none)
686 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000687 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000688 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000689
John McCall02cace72009-08-28 07:59:38 +0000690 // If the original function was part of a friend declaration,
691 // inherit its namespace state.
692 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
693 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
694
Anders Carlssond8b285f2009-09-01 04:26:58 +0000695 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
696
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000697 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000698 return Record;
699}
700
John McCall02cace72009-08-28 07:59:38 +0000701/// Normal class members are of more specific types and therefore
702/// don't make it here. This function serves two purposes:
703/// 1) instantiating function templates
704/// 2) substituting friend declarations
705/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000706Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000707 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000708 // Check whether there is already a function template specialization for
709 // this declaration.
710 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
711 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000712 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000713 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000714 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000715 TemplateArgs.getInnermost().getFlatArgumentList(),
716 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000717 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000718
719 FunctionTemplateSpecializationInfo *Info
720 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000721 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Douglas Gregor127102b2009-06-29 20:59:39 +0000723 // If we already have a function template specialization, return it.
724 if (Info)
725 return Info->Function;
726 }
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Douglas Gregor79c22782010-01-16 20:21:20 +0000728 bool MergeWithParentScope = (TemplateParams != 0) ||
729 !(isa<Decl>(Owner) &&
730 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
731 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Douglas Gregore53060f2009-06-25 22:08:12 +0000733 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000734 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000735 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000736 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000737
Douglas Gregore53060f2009-06-25 22:08:12 +0000738 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000739 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
740 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000741 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000742 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000743 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000744 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000745 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000746 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Douglas Gregore53060f2009-06-25 22:08:12 +0000748 // Attach the parameters
749 for (unsigned P = 0; P < Params.size(); ++P)
750 Params[P]->setOwningFunction(Function);
751 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000752
Douglas Gregora735b202009-10-13 14:39:41 +0000753 if (TemplateParams) {
754 // Our resulting instantiation is actually a function template, since we
755 // are substituting only the outer template parameters. For example, given
756 //
757 // template<typename T>
758 // struct X {
759 // template<typename U> friend void f(T, U);
760 // };
761 //
762 // X<int> x;
763 //
764 // We are instantiating the friend function template "f" within X<int>,
765 // which means substituting int for T, but leaving "f" as a friend function
766 // template.
767 // Build the function template itself.
768 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
769 Function->getLocation(),
770 Function->getDeclName(),
771 TemplateParams, Function);
772 Function->setDescribedFunctionTemplate(FunctionTemplate);
773 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000774 } else if (FunctionTemplate) {
775 // Record this function template specialization.
776 Function->setFunctionTemplateSpecialization(SemaRef.Context,
777 FunctionTemplate,
778 &TemplateArgs.getInnermost(),
779 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000780 }
Douglas Gregora735b202009-10-13 14:39:41 +0000781
Douglas Gregore53060f2009-06-25 22:08:12 +0000782 if (InitFunctionInstantiation(Function, D))
783 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregore53060f2009-06-25 22:08:12 +0000785 bool Redeclaration = false;
786 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000787
John McCall68263142009-11-18 22:49:29 +0000788 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
789 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
790
Douglas Gregora735b202009-10-13 14:39:41 +0000791 if (TemplateParams || !FunctionTemplate) {
792 // Look only into the namespace where the friend would be declared to
793 // find a previous declaration. This is the innermost enclosing namespace,
794 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000795 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000796
Douglas Gregora735b202009-10-13 14:39:41 +0000797 // In C++, the previous declaration we find might be a tag type
798 // (class or enum). In this case, the new declaration will hide the
799 // tag type. Note that this does does not apply if we're declaring a
800 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000801 if (Previous.isSingleTagDecl())
802 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000803 }
804
John McCall9f54ad42009-12-10 09:41:52 +0000805 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
806 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000807 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000808
Douglas Gregora735b202009-10-13 14:39:41 +0000809 // If the original function was part of a friend declaration,
810 // inherit its namespace state and add it to the owner.
811 NamedDecl *FromFriendD
812 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
813 if (FromFriendD->getFriendObjectKind()) {
814 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000815 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000816 if (TemplateParams) {
817 ToFriendD = cast<NamedDecl>(FunctionTemplate);
818 PrevDecl = FunctionTemplate->getPreviousDeclaration();
819 } else {
820 ToFriendD = Function;
821 PrevDecl = Function->getPreviousDeclaration();
822 }
823 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
824 if (!Owner->isDependentContext() && !PrevDecl)
825 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
826
827 if (!TemplateParams)
828 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
829 }
830
Douglas Gregore53060f2009-06-25 22:08:12 +0000831 return Function;
832}
833
Douglas Gregord60e1052009-08-27 16:57:43 +0000834Decl *
835TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
836 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000837 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
838 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000839 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000840 // We are creating a function template specialization from a function
841 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000842 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000843 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000844 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000845 TemplateArgs.getInnermost().getFlatArgumentList(),
846 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000847 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000848
849 FunctionTemplateSpecializationInfo *Info
850 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000851 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregor6b906862009-08-21 00:16:32 +0000853 // If we already have a function template specialization, return it.
854 if (Info)
855 return Info->Function;
856 }
857
Douglas Gregor79c22782010-01-16 20:21:20 +0000858 bool MergeWithParentScope = (TemplateParams != 0) ||
859 !(isa<Decl>(Owner) &&
860 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
861 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000862
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000863 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000864 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000865 if (T.isNull())
866 return 0;
867
868 // Build the instantiated method declaration.
869 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000870 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Douglas Gregordec06662009-08-21 18:42:58 +0000872 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000873 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000874 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
875 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
876 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000877 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
878 Constructor->getLocation(),
879 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000880 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000881 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000882 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000883 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
884 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
885 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
886 SemaRef.Context.getCanonicalType(ClassTy));
887 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
888 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000889 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000890 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000891 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000892 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000893 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000894 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
895 ConvTy);
896 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
897 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000898 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000899 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000900 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000901 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000902 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000903 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000904 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000905 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000906
Douglas Gregord60e1052009-08-27 16:57:43 +0000907 if (TemplateParams) {
908 // Our resulting instantiation is actually a function template, since we
909 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000910 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000911 // template<typename T>
912 // struct X {
913 // template<typename U> void f(T, U);
914 // };
915 //
916 // X<int> x;
917 //
918 // We are instantiating the member template "f" within X<int>, which means
919 // substituting int for T, but leaving "f" as a member function template.
920 // Build the function template itself.
921 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
922 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000923 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000924 TemplateParams, Method);
925 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000926 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000927 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000928 } else if (FunctionTemplate) {
929 // Record this function template specialization.
930 Method->setFunctionTemplateSpecialization(SemaRef.Context,
931 FunctionTemplate,
932 &TemplateArgs.getInnermost(),
933 InsertPos);
934 } else {
935 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000936 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000937 }
938
Mike Stump1eb44332009-09-09 15:08:12 +0000939 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000940 // out-of-line, the instantiation will have the same lexical
941 // context (which will be a namespace scope) as the template.
942 if (D->isOutOfLine())
943 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Douglas Gregor5545e162009-03-24 00:38:23 +0000945 // Attach the parameters
946 for (unsigned P = 0; P < Params.size(); ++P)
947 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000948 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000949
950 if (InitMethodInstantiation(Method, D))
951 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000952
John McCall68263142009-11-18 22:49:29 +0000953 LookupResult Previous(SemaRef, Name, SourceLocation(),
954 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Douglas Gregord60e1052009-08-27 16:57:43 +0000956 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000957 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Douglas Gregordec06662009-08-21 18:42:58 +0000959 // In C++, the previous declaration we find might be a tag type
960 // (class or enum). In this case, the new declaration will hide the
961 // tag type. Note that this does does not apply if we're declaring a
962 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000963 if (Previous.isSingleTagDecl())
964 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000965 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000966
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000967 bool Redeclaration = false;
968 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000969 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000970 /*FIXME:*/OverloadableAttrRequired);
971
Douglas Gregor4ba31362009-12-01 17:24:26 +0000972 if (D->isPure())
973 SemaRef.CheckPureMethod(Method, SourceRange());
974
John McCall46460a62010-01-20 21:53:11 +0000975 Method->setAccess(D->getAccess());
976
John McCall68263142009-11-18 22:49:29 +0000977 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000978 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000979 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000981 return Method;
982}
983
Douglas Gregor615c5d42009-03-24 16:43:20 +0000984Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000985 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000986}
987
Douglas Gregor03b2b072009-03-24 00:15:49 +0000988Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000989 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000990}
991
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000992Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000993 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000994}
995
Douglas Gregor6477b692009-03-25 15:04:13 +0000996ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000997 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000998 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000999 if (DI) {
1000 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1001 D->getDeclName());
1002 if (DI) T = DI->getType();
1003 } else {
1004 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1005 D->getDeclName());
1006 DI = 0;
1007 }
1008
1009 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001010 return 0;
1011
John McCall58e46772009-10-23 21:48:59 +00001012 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001013
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001014 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001015 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001016 = ParmVarDecl::Create(SemaRef.Context,
1017 SemaRef.Context.getTranslationUnitDecl(),
1018 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001019 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001020
Anders Carlsson9351c172009-08-25 03:18:48 +00001021 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001022 if (D->hasUninstantiatedDefaultArg())
1023 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001024 else if (Expr *Arg = D->getDefaultArg())
1025 Param->setUninstantiatedDefaultArg(Arg);
1026
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001027 // Note: we don't try to instantiate function parameters until after
1028 // we've instantiated the function's type. Therefore, we don't have
1029 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001030 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001031 return Param;
1032}
1033
John McCalle29ba202009-08-20 01:44:21 +00001034Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1035 TemplateTypeParmDecl *D) {
1036 // TODO: don't always clone when decls are refcounted.
1037 const Type* T = D->getTypeForDecl();
1038 assert(T->isTemplateTypeParmType());
1039 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001040
John McCalle29ba202009-08-20 01:44:21 +00001041 TemplateTypeParmDecl *Inst =
1042 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001043 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001044 TTPT->getName(),
1045 D->wasDeclaredWithTypename(),
1046 D->isParameterPack());
1047
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001048 if (D->hasDefaultArgument())
1049 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001050
Douglas Gregor550d9b22009-10-31 17:21:17 +00001051 // Introduce this template parameter's instantiation into the instantiation
1052 // scope.
1053 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1054
John McCalle29ba202009-08-20 01:44:21 +00001055 return Inst;
1056}
1057
Douglas Gregor33642df2009-10-23 23:25:44 +00001058Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1059 NonTypeTemplateParmDecl *D) {
1060 // Substitute into the type of the non-type template parameter.
1061 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001062 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001063 if (DI) {
1064 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1065 D->getDeclName());
1066 if (DI) T = DI->getType();
1067 } else {
1068 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1069 D->getDeclName());
1070 DI = 0;
1071 }
1072 if (T.isNull())
1073 return 0;
1074
1075 // Check that this type is acceptable for a non-type template parameter.
1076 bool Invalid = false;
1077 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1078 if (T.isNull()) {
1079 T = SemaRef.Context.IntTy;
1080 Invalid = true;
1081 }
1082
1083 NonTypeTemplateParmDecl *Param
1084 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1085 D->getDepth() - 1, D->getPosition(),
1086 D->getIdentifier(), T, DI);
1087 if (Invalid)
1088 Param->setInvalidDecl();
1089
1090 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001091
1092 // Introduce this template parameter's instantiation into the instantiation
1093 // scope.
1094 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001095 return Param;
1096}
1097
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001098Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001099TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1100 TemplateTemplateParmDecl *D) {
1101 // Instantiate the template parameter list of the template template parameter.
1102 TemplateParameterList *TempParams = D->getTemplateParameters();
1103 TemplateParameterList *InstParams;
1104 {
1105 // Perform the actual substitution of template parameters within a new,
1106 // local instantiation scope.
1107 Sema::LocalInstantiationScope Scope(SemaRef);
1108 InstParams = SubstTemplateParams(TempParams);
1109 if (!InstParams)
1110 return NULL;
1111 }
1112
1113 // Build the template template parameter.
1114 TemplateTemplateParmDecl *Param
1115 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1116 D->getDepth() - 1, D->getPosition(),
1117 D->getIdentifier(), InstParams);
1118 Param->setDefaultArgument(D->getDefaultArgument());
1119
1120 // Introduce this template parameter's instantiation into the instantiation
1121 // scope.
1122 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1123
1124 return Param;
1125}
1126
Douglas Gregor48c32a72009-11-17 06:07:40 +00001127Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1128 // Using directives are never dependent, so they require no explicit
1129
1130 UsingDirectiveDecl *Inst
1131 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1132 D->getNamespaceKeyLocation(),
1133 D->getQualifierRange(), D->getQualifier(),
1134 D->getIdentLocation(),
1135 D->getNominatedNamespace(),
1136 D->getCommonAncestor());
1137 Owner->addDecl(Inst);
1138 return Inst;
1139}
1140
John McCalled976492009-12-04 22:46:56 +00001141Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1142 // The nested name specifier is non-dependent, so no transformation
1143 // is required.
1144
John McCall9f54ad42009-12-10 09:41:52 +00001145 // We only need to do redeclaration lookups if we're in a class
1146 // scope (in fact, it's not really even possible in non-class
1147 // scopes).
1148 bool CheckRedeclaration = Owner->isRecord();
1149
1150 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1151 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1152
John McCalled976492009-12-04 22:46:56 +00001153 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1154 D->getLocation(),
1155 D->getNestedNameRange(),
1156 D->getUsingLocation(),
1157 D->getTargetNestedNameDecl(),
1158 D->getDeclName(),
1159 D->isTypeName());
1160
1161 CXXScopeSpec SS;
1162 SS.setScopeRep(D->getTargetNestedNameDecl());
1163 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001164
1165 if (CheckRedeclaration) {
1166 Prev.setHideTags(false);
1167 SemaRef.LookupQualifiedName(Prev, Owner);
1168
1169 // Check for invalid redeclarations.
1170 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1171 D->isTypeName(), SS,
1172 D->getLocation(), Prev))
1173 NewUD->setInvalidDecl();
1174
1175 }
1176
1177 if (!NewUD->isInvalidDecl() &&
1178 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001179 D->getLocation()))
1180 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001181
John McCalled976492009-12-04 22:46:56 +00001182 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1183 NewUD->setAccess(D->getAccess());
1184 Owner->addDecl(NewUD);
1185
John McCall9f54ad42009-12-10 09:41:52 +00001186 // Don't process the shadow decls for an invalid decl.
1187 if (NewUD->isInvalidDecl())
1188 return NewUD;
1189
John McCall323c3102009-12-22 22:26:37 +00001190 bool isFunctionScope = Owner->isFunctionOrMethod();
1191
John McCall9f54ad42009-12-10 09:41:52 +00001192 // Process the shadow decls.
1193 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1194 I != E; ++I) {
1195 UsingShadowDecl *Shadow = *I;
1196 NamedDecl *InstTarget =
1197 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1198 TemplateArgs));
1199
1200 if (CheckRedeclaration &&
1201 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1202 continue;
1203
1204 UsingShadowDecl *InstShadow
1205 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1206 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001207
1208 if (isFunctionScope)
1209 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001210 }
John McCalled976492009-12-04 22:46:56 +00001211
1212 return NewUD;
1213}
1214
1215Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001216 // Ignore these; we handle them in bulk when processing the UsingDecl.
1217 return 0;
John McCalled976492009-12-04 22:46:56 +00001218}
1219
John McCall7ba107a2009-11-18 02:36:19 +00001220Decl * TemplateDeclInstantiator
1221 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001222 NestedNameSpecifier *NNS =
1223 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1224 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001225 TemplateArgs);
1226 if (!NNS)
1227 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001229 CXXScopeSpec SS;
1230 SS.setRange(D->getTargetNestedNameRange());
1231 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
1233 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001234 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001235 D->getUsingLoc(), SS, D->getLocation(),
1236 D->getDeclName(), 0,
1237 /*instantiation*/ true,
1238 /*typename*/ true, D->getTypenameLoc());
1239 if (UD)
John McCalled976492009-12-04 22:46:56 +00001240 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1241
John McCall7ba107a2009-11-18 02:36:19 +00001242 return UD;
1243}
1244
1245Decl * TemplateDeclInstantiator
1246 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1247 NestedNameSpecifier *NNS =
1248 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1249 D->getTargetNestedNameRange(),
1250 TemplateArgs);
1251 if (!NNS)
1252 return 0;
1253
1254 CXXScopeSpec SS;
1255 SS.setRange(D->getTargetNestedNameRange());
1256 SS.setScopeRep(NNS);
1257
1258 NamedDecl *UD =
1259 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1260 D->getUsingLoc(), SS, D->getLocation(),
1261 D->getDeclName(), 0,
1262 /*instantiation*/ true,
1263 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001264 if (UD)
John McCalled976492009-12-04 22:46:56 +00001265 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1266
Anders Carlsson0d8df782009-08-29 19:37:28 +00001267 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001268}
1269
John McCallce3ff2b2009-08-25 22:02:44 +00001270Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001271 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001272 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001273 return Instantiator.Visit(D);
1274}
1275
John McCalle29ba202009-08-20 01:44:21 +00001276/// \brief Instantiates a nested template parameter list in the current
1277/// instantiation context.
1278///
1279/// \param L The parameter list to instantiate
1280///
1281/// \returns NULL if there was an error
1282TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001283TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001284 // Get errors for all the parameters before bailing out.
1285 bool Invalid = false;
1286
1287 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001288 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001289 ParamVector Params;
1290 Params.reserve(N);
1291 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1292 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001293 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001294 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001295 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001296 }
1297
1298 // Clean up if we had an error.
1299 if (Invalid) {
1300 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1301 PI != PE; ++PI)
1302 if (*PI)
1303 (*PI)->Destroy(SemaRef.Context);
1304 return NULL;
1305 }
1306
1307 TemplateParameterList *InstL
1308 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1309 L->getLAngleLoc(), &Params.front(), N,
1310 L->getRAngleLoc());
1311 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001312}
John McCalle29ba202009-08-20 01:44:21 +00001313
Douglas Gregored9c0f92009-10-29 00:04:11 +00001314/// \brief Instantiate the declaration of a class template partial
1315/// specialization.
1316///
1317/// \param ClassTemplate the (instantiated) class template that is partially
1318// specialized by the instantiation of \p PartialSpec.
1319///
1320/// \param PartialSpec the (uninstantiated) class template partial
1321/// specialization that we are instantiating.
1322///
1323/// \returns true if there was an error, false otherwise.
1324bool
1325TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1326 ClassTemplateDecl *ClassTemplate,
1327 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001328 // Create a local instantiation scope for this class template partial
1329 // specialization, which will contain the instantiations of the template
1330 // parameters.
1331 Sema::LocalInstantiationScope Scope(SemaRef);
1332
Douglas Gregored9c0f92009-10-29 00:04:11 +00001333 // Substitute into the template parameters of the class template partial
1334 // specialization.
1335 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1337 if (!InstParams)
1338 return true;
1339
1340 // Substitute into the template arguments of the class template partial
1341 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001342 const TemplateArgumentLoc *PartialSpecTemplateArgs
1343 = PartialSpec->getTemplateArgsAsWritten();
1344 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1345
John McCalld5532b62009-11-23 01:53:49 +00001346 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001347 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001348 TemplateArgumentLoc Loc;
1349 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001350 return true;
John McCalld5532b62009-11-23 01:53:49 +00001351 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001352 }
1353
1354
1355 // Check that the template argument list is well-formed for this
1356 // class template.
1357 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1358 InstTemplateArgs.size());
1359 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1360 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001361 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001362 false,
1363 Converted))
1364 return true;
1365
1366 // Figure out where to insert this class template partial specialization
1367 // in the member template's set of class template partial specializations.
1368 llvm::FoldingSetNodeID ID;
1369 ClassTemplatePartialSpecializationDecl::Profile(ID,
1370 Converted.getFlatArguments(),
1371 Converted.flatSize(),
1372 SemaRef.Context);
1373 void *InsertPos = 0;
1374 ClassTemplateSpecializationDecl *PrevDecl
1375 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1376 InsertPos);
1377
1378 // Build the canonical type that describes the converted template
1379 // arguments of the class template partial specialization.
1380 QualType CanonType
1381 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1382 Converted.getFlatArguments(),
1383 Converted.flatSize());
1384
1385 // Build the fully-sugared type for this class template
1386 // specialization as the user wrote in the specialization
1387 // itself. This means that we'll pretty-print the type retrieved
1388 // from the specialization's declaration the way that the user
1389 // actually wrote the specialization, rather than formatting the
1390 // name based on the "canonical" representation used to store the
1391 // template arguments in the specialization.
1392 QualType WrittenTy
1393 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001394 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001395 CanonType);
1396
1397 if (PrevDecl) {
1398 // We've already seen a partial specialization with the same template
1399 // parameters and template arguments. This can happen, for example, when
1400 // substituting the outer template arguments ends up causing two
1401 // class template partial specializations of a member class template
1402 // to have identical forms, e.g.,
1403 //
1404 // template<typename T, typename U>
1405 // struct Outer {
1406 // template<typename X, typename Y> struct Inner;
1407 // template<typename Y> struct Inner<T, Y>;
1408 // template<typename Y> struct Inner<U, Y>;
1409 // };
1410 //
1411 // Outer<int, int> outer; // error: the partial specializations of Inner
1412 // // have the same signature.
1413 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1414 << WrittenTy;
1415 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1416 << SemaRef.Context.getTypeDeclType(PrevDecl);
1417 return true;
1418 }
1419
1420
1421 // Create the class template partial specialization declaration.
1422 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1423 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1424 PartialSpec->getLocation(),
1425 InstParams,
1426 ClassTemplate,
1427 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001428 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001429 0);
1430 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1431 InstPartialSpec->setTypeAsWritten(WrittenTy);
1432
1433 // Add this partial specialization to the set of class template partial
1434 // specializations.
1435 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1436 InsertPos);
1437 return false;
1438}
1439
John McCallce3ff2b2009-08-25 22:02:44 +00001440/// \brief Does substitution on the type of the given function, including
1441/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001442///
John McCallce3ff2b2009-08-25 22:02:44 +00001443/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001444///
1445/// \param Params the instantiated parameter declarations
1446
John McCallce3ff2b2009-08-25 22:02:44 +00001447/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001448/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001449QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001450TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001451 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1452 bool InvalidDecl = false;
1453
John McCallce3ff2b2009-08-25 22:02:44 +00001454 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001455 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001456 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001457 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001458 PEnd = D->param_end();
1459 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001460 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001461 if (PInst->getType()->isVoidType()) {
1462 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1463 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001464 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001465 PInst->getType(),
1466 diag::err_abstract_type_in_decl,
1467 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001468 PInst->setInvalidDecl();
1469
1470 Params.push_back(PInst);
1471 ParamTys.push_back(PInst->getType());
1472
1473 if (PInst->isInvalidDecl())
1474 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001475 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001476 InvalidDecl = true;
1477 }
1478
1479 // FIXME: Deallocate dead declarations.
1480 if (InvalidDecl)
1481 return QualType();
1482
John McCall183700f2009-09-21 23:43:11 +00001483 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001484 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001485 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001486 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1487 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001488 if (ResultType.isNull())
1489 return QualType();
1490
Jay Foadbeaaccd2009-05-21 09:52:38 +00001491 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001492 Proto->isVariadic(), Proto->getTypeQuals(),
1493 D->getLocation(), D->getDeclName());
1494}
1495
Mike Stump1eb44332009-09-09 15:08:12 +00001496/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001497/// declaration (New) from the corresponding fields of its template (Tmpl).
1498///
1499/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001500bool
1501TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001502 FunctionDecl *Tmpl) {
1503 if (Tmpl->isDeleted())
1504 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Douglas Gregorcca9e962009-07-01 22:01:06 +00001506 // If we are performing substituting explicitly-specified template arguments
1507 // or deduced template arguments into a function template and we reach this
1508 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001509 // to keeping the new function template specialization. We therefore
1510 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001511 // into a template instantiation for this specific function template
1512 // specialization, which is not a SFINAE context, so that we diagnose any
1513 // further errors in the declaration itself.
1514 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1515 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1516 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1517 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001518 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001519 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001520 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001521 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001522 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001523 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1524 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001525 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001526 }
1527 }
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001529 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1530 assert(Proto && "Function template without prototype?");
1531
1532 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1533 Proto->getNoReturnAttr()) {
1534 // The function has an exception specification or a "noreturn"
1535 // attribute. Substitute into each of the exception types.
1536 llvm::SmallVector<QualType, 4> Exceptions;
1537 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1538 // FIXME: Poor location information!
1539 QualType T
1540 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1541 New->getLocation(), New->getDeclName());
1542 if (T.isNull() ||
1543 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1544 continue;
1545
1546 Exceptions.push_back(T);
1547 }
1548
1549 // Rebuild the function type
1550
1551 const FunctionProtoType *NewProto
1552 = New->getType()->getAs<FunctionProtoType>();
1553 assert(NewProto && "Template instantiation without function prototype?");
1554 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1555 NewProto->arg_type_begin(),
1556 NewProto->getNumArgs(),
1557 NewProto->isVariadic(),
1558 NewProto->getTypeQuals(),
1559 Proto->hasExceptionSpec(),
1560 Proto->hasAnyExceptionSpec(),
1561 Exceptions.size(),
1562 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001563 Proto->getNoReturnAttr(),
1564 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001565 }
1566
Douglas Gregore53060f2009-06-25 22:08:12 +00001567 return false;
1568}
1569
Douglas Gregor5545e162009-03-24 00:38:23 +00001570/// \brief Initializes common fields of an instantiated method
1571/// declaration (New) from the corresponding fields of its template
1572/// (Tmpl).
1573///
1574/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001575bool
1576TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001577 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001578 if (InitFunctionInstantiation(New, Tmpl))
1579 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Douglas Gregor5545e162009-03-24 00:38:23 +00001581 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1582 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001583 if (Tmpl->isVirtualAsWritten())
1584 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001585
1586 // FIXME: attributes
1587 // FIXME: New needs a pointer to Tmpl
1588 return false;
1589}
Douglas Gregora58861f2009-05-13 20:28:22 +00001590
1591/// \brief Instantiate the definition of the given function from its
1592/// template.
1593///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001594/// \param PointOfInstantiation the point at which the instantiation was
1595/// required. Note that this is not precisely a "point of instantiation"
1596/// for the function, but it's close.
1597///
Douglas Gregora58861f2009-05-13 20:28:22 +00001598/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001599/// function template specialization or member function of a class template
1600/// specialization.
1601///
1602/// \param Recursive if true, recursively instantiates any functions that
1603/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001604///
1605/// \param DefinitionRequired if true, then we are performing an explicit
1606/// instantiation where the body of the function is required. Complain if
1607/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001608void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001609 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001610 bool Recursive,
1611 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001612 if (Function->isInvalidDecl())
1613 return;
1614
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001615 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001617 // Never instantiate an explicit specialization.
1618 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1619 return;
1620
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001621 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001622 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001623 Stmt *Pattern = 0;
1624 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001625 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001626
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001627 if (!Pattern) {
1628 if (DefinitionRequired) {
1629 if (Function->getPrimaryTemplate())
1630 Diag(PointOfInstantiation,
1631 diag::err_explicit_instantiation_undefined_func_template)
1632 << Function->getPrimaryTemplate();
1633 else
1634 Diag(PointOfInstantiation,
1635 diag::err_explicit_instantiation_undefined_member)
1636 << 1 << Function->getDeclName() << Function->getDeclContext();
1637
1638 if (PatternDecl)
1639 Diag(PatternDecl->getLocation(),
1640 diag::note_explicit_instantiation_here);
1641 }
1642
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001643 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001644 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001645
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001646 // C++0x [temp.explicit]p9:
1647 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001648 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001649 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001650 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001651 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001652 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001653 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001655 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1656 if (Inst)
1657 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001658
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001659 // If we're performing recursive template instantiation, create our own
1660 // queue of pending implicit instantiations that we will instantiate later,
1661 // while we're still within our own instantiation context.
1662 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1663 if (Recursive)
1664 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001666 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1667
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001668 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001669 // recorded, unless we're actually a member function within a local
1670 // class, in which case we need to merge our results with the parent
1671 // scope (of the enclosing function).
1672 bool MergeWithParentScope = false;
1673 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1674 MergeWithParentScope = Rec->isLocalClass();
1675
1676 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001678 // Introduce the instantiated function parameters into the local
1679 // instantiation scope.
1680 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1681 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1682 Function->getParamDecl(I));
1683
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001684 // Enter the scope of this instantiation. We don't use
1685 // PushDeclContext because we don't have a scope.
1686 DeclContext *PreviousContext = CurContext;
1687 CurContext = Function;
1688
Mike Stump1eb44332009-09-09 15:08:12 +00001689 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001690 getTemplateInstantiationArgs(Function);
1691
1692 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001693 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001694 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1695 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1696 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001697 }
1698
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001699 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001700 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001701
Douglas Gregor52604ab2009-09-11 21:19:12 +00001702 if (Body.isInvalid())
1703 Function->setInvalidDecl();
1704
Mike Stump1eb44332009-09-09 15:08:12 +00001705 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001706 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001707
1708 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001709
1710 DeclGroupRef DG(Function);
1711 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Douglas Gregor60406be2010-01-16 22:29:39 +00001713 // This class may have local implicit instantiations that need to be
1714 // instantiation within this scope.
1715 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1716 Scope.Exit();
1717
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001718 if (Recursive) {
1719 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001720 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001721 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001723 // Restore the set of pending implicit instantiations.
1724 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1725 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001726}
1727
1728/// \brief Instantiate the definition of the given variable from its
1729/// template.
1730///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001731/// \param PointOfInstantiation the point at which the instantiation was
1732/// required. Note that this is not precisely a "point of instantiation"
1733/// for the function, but it's close.
1734///
1735/// \param Var the already-instantiated declaration of a static member
1736/// variable of a class template specialization.
1737///
1738/// \param Recursive if true, recursively instantiates any functions that
1739/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001740///
1741/// \param DefinitionRequired if true, then we are performing an explicit
1742/// instantiation where an out-of-line definition of the member variable
1743/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001744void Sema::InstantiateStaticDataMemberDefinition(
1745 SourceLocation PointOfInstantiation,
1746 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001747 bool Recursive,
1748 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001749 if (Var->isInvalidDecl())
1750 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Douglas Gregor7caa6822009-07-24 20:34:43 +00001752 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001753 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001754 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001755 assert(Def->isStaticDataMember() && "Not a static data member?");
1756 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Douglas Gregor0d035142009-10-27 18:42:08 +00001758 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001759 // We did not find an out-of-line definition of this static data member,
1760 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001761 // instantiate this definition (or provide a specialization for it) in
1762 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001763 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001764 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001765 Diag(PointOfInstantiation,
1766 diag::err_explicit_instantiation_undefined_member)
1767 << 2 << Var->getDeclName() << Var->getDeclContext();
1768 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1769 }
1770
Douglas Gregor7caa6822009-07-24 20:34:43 +00001771 return;
1772 }
1773
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001774 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001775 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001776 return;
1777
1778 // C++0x [temp.explicit]p9:
1779 // Except for inline functions, other explicit instantiation declarations
1780 // have the effect of suppressing the implicit instantiation of the entity
1781 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001782 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001783 == TSK_ExplicitInstantiationDeclaration)
1784 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Douglas Gregor7caa6822009-07-24 20:34:43 +00001786 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1787 if (Inst)
1788 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregor7caa6822009-07-24 20:34:43 +00001790 // If we're performing recursive template instantiation, create our own
1791 // queue of pending implicit instantiations that we will instantiate later,
1792 // while we're still within our own instantiation context.
1793 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1794 if (Recursive)
1795 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Douglas Gregor7caa6822009-07-24 20:34:43 +00001797 // Enter the scope of this instantiation. We don't use
1798 // PushDeclContext because we don't have a scope.
1799 DeclContext *PreviousContext = CurContext;
1800 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001802 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001803 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001804 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001805 CurContext = PreviousContext;
1806
1807 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001808 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001809 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1810 assert(MSInfo && "Missing member specialization information?");
1811 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1812 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001813 DeclGroupRef DG(Var);
1814 Consumer.HandleTopLevelDecl(DG);
1815 }
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Douglas Gregor7caa6822009-07-24 20:34:43 +00001817 if (Recursive) {
1818 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001819 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001820 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Douglas Gregor7caa6822009-07-24 20:34:43 +00001822 // Restore the set of pending implicit instantiations.
1823 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001824 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001825}
Douglas Gregor815215d2009-05-27 05:35:12 +00001826
Anders Carlsson09025312009-08-29 05:16:22 +00001827void
1828Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1829 const CXXConstructorDecl *Tmpl,
1830 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Anders Carlsson09025312009-08-29 05:16:22 +00001832 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001833 bool AnyErrors = false;
1834
Anders Carlsson09025312009-08-29 05:16:22 +00001835 // Instantiate all the initializers.
1836 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001837 InitsEnd = Tmpl->init_end();
1838 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001839 CXXBaseOrMemberInitializer *Init = *Inits;
1840
1841 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001842 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Anders Carlsson09025312009-08-29 05:16:22 +00001844 // Instantiate all the arguments.
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001845 Expr *InitE = Init->getInit();
1846 if (!InitE) {
1847 // Nothing to instantiate;
1848 } else if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(InitE)) {
1849 if (InstantiateInitializationArguments(*this, ParenList->getExprs(),
1850 ParenList->getNumExprs(),
1851 TemplateArgs, CommaLocs,
1852 NewArgs)) {
1853 AnyErrors = true;
1854 continue;
1855 }
1856 } else {
1857 OwningExprResult InitArg = SubstExpr(InitE, TemplateArgs);
1858 if (InitArg.isInvalid()) {
1859 AnyErrors = true;
1860 continue;
1861 }
1862
1863 NewArgs.push_back(InitArg.release());
Anders Carlsson09025312009-08-29 05:16:22 +00001864 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001865
Anders Carlsson09025312009-08-29 05:16:22 +00001866 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00001867 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001868 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001869 TemplateArgs,
1870 Init->getSourceLocation(),
1871 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001872 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001873 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00001874 New->setInvalidDecl();
1875 continue;
1876 }
1877
John McCalla93c9342009-12-07 02:54:59 +00001878 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001879 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001880 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001881 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001882 Init->getRParenLoc(),
1883 New->getParent());
1884 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001885 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001887 // Is this an anonymous union?
1888 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001889 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001890 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001891 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1892 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001893
1894 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001895 NewArgs.size(),
1896 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001897 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001898 Init->getRParenLoc());
1899 }
1900
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001901 if (NewInit.isInvalid()) {
1902 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00001903 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001904 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00001905 // FIXME: It would be nice if ASTOwningVector had a release function.
1906 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Anders Carlsson09025312009-08-29 05:16:22 +00001908 NewInits.push_back((MemInitTy *)NewInit.get());
1909 }
1910 }
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Anders Carlsson09025312009-08-29 05:16:22 +00001912 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001913 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001914 /*FIXME: ColonLoc */
1915 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001916 NewInits.data(), NewInits.size(),
1917 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00001918}
1919
John McCall52a575a2009-08-29 08:11:13 +00001920// TODO: this could be templated if the various decl types used the
1921// same method name.
1922static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1923 ClassTemplateDecl *Instance) {
1924 Pattern = Pattern->getCanonicalDecl();
1925
1926 do {
1927 Instance = Instance->getCanonicalDecl();
1928 if (Pattern == Instance) return true;
1929 Instance = Instance->getInstantiatedFromMemberTemplate();
1930 } while (Instance);
1931
1932 return false;
1933}
1934
Douglas Gregor0d696532009-09-28 06:34:35 +00001935static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1936 FunctionTemplateDecl *Instance) {
1937 Pattern = Pattern->getCanonicalDecl();
1938
1939 do {
1940 Instance = Instance->getCanonicalDecl();
1941 if (Pattern == Instance) return true;
1942 Instance = Instance->getInstantiatedFromMemberTemplate();
1943 } while (Instance);
1944
1945 return false;
1946}
1947
Douglas Gregored9c0f92009-10-29 00:04:11 +00001948static bool
1949isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1950 ClassTemplatePartialSpecializationDecl *Instance) {
1951 Pattern
1952 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1953 do {
1954 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1955 Instance->getCanonicalDecl());
1956 if (Pattern == Instance)
1957 return true;
1958 Instance = Instance->getInstantiatedFromMember();
1959 } while (Instance);
1960
1961 return false;
1962}
1963
John McCall52a575a2009-08-29 08:11:13 +00001964static bool isInstantiationOf(CXXRecordDecl *Pattern,
1965 CXXRecordDecl *Instance) {
1966 Pattern = Pattern->getCanonicalDecl();
1967
1968 do {
1969 Instance = Instance->getCanonicalDecl();
1970 if (Pattern == Instance) return true;
1971 Instance = Instance->getInstantiatedFromMemberClass();
1972 } while (Instance);
1973
1974 return false;
1975}
1976
1977static bool isInstantiationOf(FunctionDecl *Pattern,
1978 FunctionDecl *Instance) {
1979 Pattern = Pattern->getCanonicalDecl();
1980
1981 do {
1982 Instance = Instance->getCanonicalDecl();
1983 if (Pattern == Instance) return true;
1984 Instance = Instance->getInstantiatedFromMemberFunction();
1985 } while (Instance);
1986
1987 return false;
1988}
1989
1990static bool isInstantiationOf(EnumDecl *Pattern,
1991 EnumDecl *Instance) {
1992 Pattern = Pattern->getCanonicalDecl();
1993
1994 do {
1995 Instance = Instance->getCanonicalDecl();
1996 if (Pattern == Instance) return true;
1997 Instance = Instance->getInstantiatedFromMemberEnum();
1998 } while (Instance);
1999
2000 return false;
2001}
2002
John McCalled976492009-12-04 22:46:56 +00002003static bool isInstantiationOf(UsingShadowDecl *Pattern,
2004 UsingShadowDecl *Instance,
2005 ASTContext &C) {
2006 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2007}
2008
2009static bool isInstantiationOf(UsingDecl *Pattern,
2010 UsingDecl *Instance,
2011 ASTContext &C) {
2012 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2013}
2014
John McCall7ba107a2009-11-18 02:36:19 +00002015static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2016 UsingDecl *Instance,
2017 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002018 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002019}
2020
2021static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002022 UsingDecl *Instance,
2023 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002024 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002025}
2026
John McCall52a575a2009-08-29 08:11:13 +00002027static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2028 VarDecl *Instance) {
2029 assert(Instance->isStaticDataMember());
2030
2031 Pattern = Pattern->getCanonicalDecl();
2032
2033 do {
2034 Instance = Instance->getCanonicalDecl();
2035 if (Pattern == Instance) return true;
2036 Instance = Instance->getInstantiatedFromStaticDataMember();
2037 } while (Instance);
2038
2039 return false;
2040}
2041
John McCalled976492009-12-04 22:46:56 +00002042// Other is the prospective instantiation
2043// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002044static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002045 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002046 if (UnresolvedUsingTypenameDecl *UUD
2047 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2048 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2049 return isInstantiationOf(UUD, UD, Ctx);
2050 }
2051 }
2052
2053 if (UnresolvedUsingValueDecl *UUD
2054 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002055 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2056 return isInstantiationOf(UUD, UD, Ctx);
2057 }
2058 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002059
Anders Carlsson0d8df782009-08-29 19:37:28 +00002060 return false;
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
John McCall52a575a2009-08-29 08:11:13 +00002063 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2064 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002065
John McCall52a575a2009-08-29 08:11:13 +00002066 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2067 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002068
John McCall52a575a2009-08-29 08:11:13 +00002069 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2070 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002071
Douglas Gregor7caa6822009-07-24 20:34:43 +00002072 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002073 if (Var->isStaticDataMember())
2074 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2075
2076 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2077 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002078
Douglas Gregor0d696532009-09-28 06:34:35 +00002079 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2080 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2081
Douglas Gregored9c0f92009-10-29 00:04:11 +00002082 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2083 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2084 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2085 PartialSpec);
2086
Anders Carlssond8b285f2009-09-01 04:26:58 +00002087 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2088 if (!Field->getDeclName()) {
2089 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002090 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002091 cast<FieldDecl>(D);
2092 }
2093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
John McCalled976492009-12-04 22:46:56 +00002095 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2096 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2097
2098 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2099 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2100
Douglas Gregor815215d2009-05-27 05:35:12 +00002101 return D->getDeclName() && isa<NamedDecl>(Other) &&
2102 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2103}
2104
2105template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002106static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002107 NamedDecl *D,
2108 ForwardIterator first,
2109 ForwardIterator last) {
2110 for (; first != last; ++first)
2111 if (isInstantiationOf(Ctx, D, *first))
2112 return cast<NamedDecl>(*first);
2113
2114 return 0;
2115}
2116
John McCall02cace72009-08-28 07:59:38 +00002117/// \brief Finds the instantiation of the given declaration context
2118/// within the current instantiation.
2119///
2120/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002121DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2122 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002123 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002124 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002125 return cast_or_null<DeclContext>(ID);
2126 } else return DC;
2127}
2128
Douglas Gregored961e72009-05-27 17:54:46 +00002129/// \brief Find the instantiation of the given declaration within the
2130/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002131///
2132/// This routine is intended to be used when \p D is a declaration
2133/// referenced from within a template, that needs to mapped into the
2134/// corresponding declaration within an instantiation. For example,
2135/// given:
2136///
2137/// \code
2138/// template<typename T>
2139/// struct X {
2140/// enum Kind {
2141/// KnownValue = sizeof(T)
2142/// };
2143///
2144/// bool getKind() const { return KnownValue; }
2145/// };
2146///
2147/// template struct X<int>;
2148/// \endcode
2149///
2150/// In the instantiation of X<int>::getKind(), we need to map the
2151/// EnumConstantDecl for KnownValue (which refers to
2152/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002153/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2154/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002155NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2156 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002157 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002158 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2159 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2160 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002161 // D is a local of some kind. Look into the map of local
2162 // declarations to their instantiations.
2163 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2164 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002165
Douglas Gregore95b4092009-09-16 18:34:49 +00002166 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2167 if (!Record->isDependentContext())
2168 return D;
2169
2170 // If the RecordDecl is actually the injected-class-name or a "templated"
2171 // declaration for a class template or class template partial
2172 // specialization, substitute into the injected-class-name of the
2173 // class template or partial specialization to find the new DeclContext.
2174 QualType T;
2175 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2176
2177 if (ClassTemplate) {
2178 T = ClassTemplate->getInjectedClassNameType(Context);
2179 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2180 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2181 T = Context.getTypeDeclType(Record);
2182 ClassTemplate = PartialSpec->getSpecializedTemplate();
2183 }
2184
2185 if (!T.isNull()) {
2186 // Substitute into the injected-class-name to get the type corresponding
2187 // to the instantiation we want. This substitution should never fail,
2188 // since we know we can instantiate the injected-class-name or we wouldn't
2189 // have gotten to the injected-class-name!
2190 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2191 // instantiation in the common case?
2192 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2193 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2194
2195 if (!T->isDependentType()) {
2196 assert(T->isRecordType() && "Instantiation must produce a record type");
2197 return T->getAs<RecordType>()->getDecl();
2198 }
2199
2200 // We are performing "partial" template instantiation to create the
2201 // member declarations for the members of a class template
2202 // specialization. Therefore, D is actually referring to something in
2203 // the current instantiation. Look through the current context,
2204 // which contains actual instantiations, to find the instantiation of
2205 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002206 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002207 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002208 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002209 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002210 if (isInstantiationOf(ClassTemplate,
2211 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002212 return Spec;
2213 }
2214
Mike Stump1eb44332009-09-09 15:08:12 +00002215 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002216 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002217 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002218 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002219
2220 // Fall through to deal with other dependent record types (e.g.,
2221 // anonymous unions in class templates).
2222 }
John McCall52a575a2009-08-29 08:11:13 +00002223
Douglas Gregore95b4092009-09-16 18:34:49 +00002224 if (!ParentDC->isDependentContext())
2225 return D;
2226
2227 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002228 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002229 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Douglas Gregor815215d2009-05-27 05:35:12 +00002231 if (ParentDC != D->getDeclContext()) {
2232 // We performed some kind of instantiation in the parent context,
2233 // so now we need to look into the instantiated parent context to
2234 // find the instantiation of the declaration D.
2235 NamedDecl *Result = 0;
2236 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002237 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002238 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2239 } else {
2240 // Since we don't have a name for the entity we're looking for,
2241 // our only option is to walk through all of the declarations to
2242 // find that name. This will occur in a few cases:
2243 //
2244 // - anonymous struct/union within a template
2245 // - unnamed class/struct/union/enum within a template
2246 //
2247 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002248 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002249 ParentDC->decls_begin(),
2250 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002251 }
Mike Stump1eb44332009-09-09 15:08:12 +00002252
John McCall9f54ad42009-12-10 09:41:52 +00002253 // UsingShadowDecls can instantiate to nothing because of using hiding.
2254 assert((Result || isa<UsingShadowDecl>(D))
2255 && "Unable to find instantiation of declaration!");
2256
Douglas Gregor815215d2009-05-27 05:35:12 +00002257 D = Result;
2258 }
2259
Douglas Gregor815215d2009-05-27 05:35:12 +00002260 return D;
2261}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002262
Mike Stump1eb44332009-09-09 15:08:12 +00002263/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002264/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002265void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2266 while (!PendingLocalImplicitInstantiations.empty() ||
2267 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2268 PendingImplicitInstantiation Inst;
2269
2270 if (PendingLocalImplicitInstantiations.empty()) {
2271 Inst = PendingImplicitInstantiations.front();
2272 PendingImplicitInstantiations.pop_front();
2273 } else {
2274 Inst = PendingLocalImplicitInstantiations.front();
2275 PendingLocalImplicitInstantiations.pop_front();
2276 }
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Douglas Gregor7caa6822009-07-24 20:34:43 +00002278 // Instantiate function definitions
2279 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002280 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002281 Function->getLocation(), *this,
2282 Context.getSourceManager(),
2283 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002285 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002286 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002287 continue;
2288 }
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Douglas Gregor7caa6822009-07-24 20:34:43 +00002290 // Instantiate static data member definitions.
2291 VarDecl *Var = cast<VarDecl>(Inst.first);
2292 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002293
Mike Stump1eb44332009-09-09 15:08:12 +00002294 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002295 Var->getLocation(), *this,
2296 Context.getSourceManager(),
2297 "instantiating static data member "
2298 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Douglas Gregor7caa6822009-07-24 20:34:43 +00002300 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002301 }
2302}