blob: 8d74bd76ca5ccbf29a07de83ec3ad3d2f0a3799c [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
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000148 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000150 return Typedef;
151}
152
Douglas Gregor6eef5192009-12-14 19:27:10 +0000153/// \brief Instantiate the arguments provided as part of initialization.
154///
155/// \returns true if an error occurred, false otherwise.
156static bool InstantiateInitializationArguments(Sema &SemaRef,
157 Expr **Args, unsigned NumArgs,
158 const MultiLevelTemplateArgumentList &TemplateArgs,
159 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
160 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
161 for (unsigned I = 0; I != NumArgs; ++I) {
162 // When we hit the first defaulted argument, break out of the loop:
163 // we don't pass those default arguments on.
164 if (Args[I]->isDefaultArgument())
165 break;
166
167 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
168 if (Arg.isInvalid())
169 return true;
170
171 Expr *ArgExpr = (Expr *)Arg.get();
172 InitArgs.push_back(Arg.release());
173
174 // FIXME: We're faking all of the comma locations. Do we need them?
175 FakeCommaLocs.push_back(
176 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
177 }
178
179 return false;
180}
181
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000182Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000183 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000184 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000185 TemplateArgs,
186 D->getTypeSpecStartLoc(),
187 D->getDeclName());
188 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000189 return 0;
190
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000191 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000192 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
193 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000194 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000195 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000196 Var->setThreadSpecified(D->isThreadSpecified());
197 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
198 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000199
200 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000201 // out-of-line, the instantiation will have the same lexical
202 // context (which will be a namespace scope) as the template.
203 if (D->isOutOfLine())
204 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Mike Stump390b4cc2009-05-16 07:39:55 +0000206 // FIXME: In theory, we could have a previous declaration for variables that
207 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000208 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000209 // FIXME: having to fake up a LookupResult is dumb.
210 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
211 Sema::LookupOrdinaryName);
212 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Douglas Gregor7caa6822009-07-24 20:34:43 +0000214 if (D->isOutOfLine()) {
215 D->getLexicalDeclContext()->addDecl(Var);
216 Owner->makeDeclVisibleInContext(Var);
217 } else {
218 Owner->addDecl(Var);
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000221 // Link instantiations of static data members back to the template from
222 // which they were instantiated.
223 if (Var->isStaticDataMember())
224 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000225 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000226
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000227 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000228 if (Var->isStaticDataMember() && !D->isOutOfLine())
229 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
230 else
231 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
232
Douglas Gregor6eef5192009-12-14 19:27:10 +0000233 // Extract the initializer, skipping through any temporary-binding
234 // expressions and look at the subexpression as it was written.
235 Expr *DInit = D->getInit();
236 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
237 DInit = Binder->getSubExpr();
238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
239 DInit = ICE->getSubExprAsWritten();
240
241 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
242 // The initializer is a parenthesized list of expressions that is
243 // type-dependent. Instantiate each of the expressions; we'll be
244 // performing direct initialization with them.
245 llvm::SmallVector<SourceLocation, 4> CommaLocs;
246 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
247 if (!InstantiateInitializationArguments(SemaRef,
248 PLE->getExprs(),
249 PLE->getNumExprs(),
250 TemplateArgs,
251 CommaLocs, InitArgs)) {
252 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000253 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000254 PLE->getLParenLoc(),
255 move_arg(InitArgs),
256 CommaLocs.data(),
257 PLE->getRParenLoc());
258 }
259 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
260 // The initializer resolved to a constructor. Instantiate the constructor
261 // arguments.
262 llvm::SmallVector<SourceLocation, 4> CommaLocs;
263 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
264
265 if (!InstantiateInitializationArguments(SemaRef,
266 Construct->getArgs(),
267 Construct->getNumArgs(),
268 TemplateArgs,
269 CommaLocs, InitArgs)) {
270 if (D->hasCXXDirectInitializer()) {
271 SourceLocation FakeLParenLoc =
272 SemaRef.PP.getLocForEndOfToken(D->getLocation());
273 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
274 : CommaLocs.back();
275 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
276 FakeLParenLoc,
277 move_arg(InitArgs),
278 CommaLocs.data(),
279 FakeRParenLoc);
280 } else if (InitArgs.size() == 1) {
281 Expr *Init = (Expr*)(InitArgs.take()[0]);
282 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
283 SemaRef.Owned(Init),
284 false);
285 } else {
286 assert(InitArgs.size() == 0);
287 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
288 }
289 }
290 } else {
291 OwningExprResult Init
292 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
293
294 // FIXME: Not happy about invalidating decls just because of a bad
295 // initializer, unless it affects the type.
296 if (Init.isInvalid())
297 Var->setInvalidDecl();
298 else
299 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
300 D->hasCXXDirectInitializer());
301 }
302
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000303 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000304 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
305 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000306
307 return Var;
308}
309
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000310Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
311 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000312 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000313 if (DI->getType()->isDependentType()) {
314 DI = SemaRef.SubstType(DI, TemplateArgs,
315 D->getLocation(), D->getDeclName());
316 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000317 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000318 Invalid = true;
319 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000320 // C++ [temp.arg.type]p3:
321 // If a declaration acquires a function type through a type
322 // dependent on a template-parameter and this causes a
323 // declaration that does not use the syntactic form of a
324 // function declarator to have function type, the program is
325 // ill-formed.
326 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000327 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000328 Invalid = true;
329 }
330 }
331
332 Expr *BitWidth = D->getBitWidth();
333 if (Invalid)
334 BitWidth = 0;
335 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000336 // The bit-width expression is not potentially evaluated.
337 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000339 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000340 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000341 if (InstantiatedBitWidth.isInvalid()) {
342 Invalid = true;
343 BitWidth = 0;
344 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000345 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000346 }
347
John McCall07fb6be2009-10-22 23:33:21 +0000348 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
349 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000351 D->getLocation(),
352 D->isMutable(),
353 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000354 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000355 D->getAccess(),
356 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000357 if (!Field) {
358 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000359 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000362 InstantiateAttrs(D, Field);
363
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000364 if (Invalid)
365 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000367 if (!Field->getDeclName()) {
368 // Keep track of where this decl came from.
369 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000372 Field->setImplicit(D->isImplicit());
373 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000374
375 return Field;
376}
377
John McCall02cace72009-08-28 07:59:38 +0000378Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
379 FriendDecl::FriendUnion FU;
380
381 // Handle friend type expressions by simply substituting template
382 // parameters into the pattern type.
383 if (Type *Ty = D->getFriendType()) {
384 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
385 D->getLocation(), DeclarationName());
386 if (T.isNull()) return 0;
387
388 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
389 FU = T.getTypePtr();
390
391 // Handle everything else by appropriate substitution.
392 } else {
393 NamedDecl *ND = D->getFriendDecl();
394 assert(ND && "friend decl must be a decl or a type!");
395
Douglas Gregora735b202009-10-13 14:39:41 +0000396 // FIXME: We have a problem here, because the nested call to Visit(ND)
397 // will inject the thing that the friend references into the current
398 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000399 Decl *NewND = Visit(ND);
400 if (!NewND) return 0;
401
402 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
John McCall02cace72009-08-28 07:59:38 +0000405 FriendDecl *FD =
406 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
407 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000408 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000409 Owner->addDecl(FD);
410 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000411}
412
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000413Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
414 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Douglas Gregorac7610d2009-06-22 20:57:11 +0000416 // The expression in a static assertion is not potentially evaluated.
417 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000419 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000420 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000421 if (InstantiatedAssertExpr.isInvalid())
422 return 0;
423
Douglas Gregor43d9d922009-08-08 01:41:12 +0000424 OwningExprResult Message(SemaRef, D->getMessage());
425 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000426 Decl *StaticAssert
427 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000428 move(InstantiatedAssertExpr),
429 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 return StaticAssert;
431}
432
433Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000435 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000436 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000437 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000438 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000439 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000440 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441 Enum->startDefinition();
442
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000443 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000444
445 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000446 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
447 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000448 EC != ECEnd; ++EC) {
449 // The specified value for the enumerator.
450 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000451 if (Expr *UninstValue = EC->getInitExpr()) {
452 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000453 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000454 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
John McCallce3ff2b2009-08-25 22:02:44 +0000456 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000457 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000458
459 // Drop the initial value and continue.
460 bool isInvalid = false;
461 if (Value.isInvalid()) {
462 Value = SemaRef.Owned((Expr *)0);
463 isInvalid = true;
464 }
465
Mike Stump1eb44332009-09-09 15:08:12 +0000466 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000467 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
468 EC->getLocation(), EC->getIdentifier(),
469 move(Value));
470
471 if (isInvalid) {
472 if (EnumConst)
473 EnumConst->setInvalidDecl();
474 Enum->setInvalidDecl();
475 }
476
477 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000478 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000479 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000480 LastEnumConst = EnumConst;
481 }
482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000484 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000485 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000486 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
487 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000488 &Enumerators[0], Enumerators.size(),
489 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000490
491 return Enum;
492}
493
Douglas Gregor6477b692009-03-25 15:04:13 +0000494Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
495 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
496 return 0;
497}
498
Douglas Gregored9c0f92009-10-29 00:04:11 +0000499namespace {
500 class SortDeclByLocation {
501 SourceManager &SourceMgr;
502
503 public:
504 explicit SortDeclByLocation(SourceManager &SourceMgr)
505 : SourceMgr(SourceMgr) { }
506
507 bool operator()(const Decl *X, const Decl *Y) const {
508 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
509 Y->getLocation());
510 }
511 };
512}
513
John McCalle29ba202009-08-20 01:44:21 +0000514Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000515 // Create a local instantiation scope for this class template, which
516 // will contain the instantiations of the template parameters.
517 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000518 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000519 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000520 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000521 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000522
523 CXXRecordDecl *Pattern = D->getTemplatedDecl();
524 CXXRecordDecl *RecordInst
525 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
526 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000527 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
528 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000529
530 ClassTemplateDecl *Inst
531 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
532 D->getIdentifier(), InstParams, RecordInst, 0);
533 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000534 if (D->getFriendObjectKind())
535 Inst->setObjectOfFriendDecl(true);
536 else
537 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000538 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000539
540 // Trigger creation of the type for the instantiation.
541 SemaRef.Context.getTypeDeclType(RecordInst);
542
Douglas Gregor259571e2009-10-30 22:42:42 +0000543 // Finish handling of friends.
544 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000545 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000546 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000547
John McCalle29ba202009-08-20 01:44:21 +0000548 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000549
550 // First, we sort the partial specializations by location, so
551 // that we instantiate them in the order they were declared.
552 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
553 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
554 P = D->getPartialSpecializations().begin(),
555 PEnd = D->getPartialSpecializations().end();
556 P != PEnd; ++P)
557 PartialSpecs.push_back(&*P);
558 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
559 SortDeclByLocation(SemaRef.SourceMgr));
560
561 // Instantiate all of the partial specializations of this member class
562 // template.
563 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
564 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
565
John McCalle29ba202009-08-20 01:44:21 +0000566 return Inst;
567}
568
Douglas Gregord60e1052009-08-27 16:57:43 +0000569Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000570TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
571 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000572 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
573
574 // Lookup the already-instantiated declaration in the instantiation
575 // of the class template and return that.
576 DeclContext::lookup_result Found
577 = Owner->lookup(ClassTemplate->getDeclName());
578 if (Found.first == Found.second)
579 return 0;
580
581 ClassTemplateDecl *InstClassTemplate
582 = dyn_cast<ClassTemplateDecl>(*Found.first);
583 if (!InstClassTemplate)
584 return 0;
585
586 Decl *DCanon = D->getCanonicalDecl();
587 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
588 P = InstClassTemplate->getPartialSpecializations().begin(),
589 PEnd = InstClassTemplate->getPartialSpecializations().end();
590 P != PEnd; ++P) {
591 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
592 return &*P;
593 }
594
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000595 return 0;
596}
597
598Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000599TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000600 // Create a local instantiation scope for this function template, which
601 // will contain the instantiations of the template parameters and then get
602 // merged with the local instantiation scope for the function template
603 // itself.
604 Sema::LocalInstantiationScope Scope(SemaRef);
605
Douglas Gregord60e1052009-08-27 16:57:43 +0000606 TemplateParameterList *TempParams = D->getTemplateParameters();
607 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000608 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000609 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000610
Douglas Gregora735b202009-10-13 14:39:41 +0000611 FunctionDecl *Instantiated = 0;
612 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
613 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
614 InstParams));
615 else
616 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
617 D->getTemplatedDecl(),
618 InstParams));
619
620 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000621 return 0;
622
Mike Stump1eb44332009-09-09 15:08:12 +0000623 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000624 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000625 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000626 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000627 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000628 assert(InstTemplate &&
629 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000630
631 // Link the instantiation back to the pattern *unless* this is a
632 // non-definition friend declaration.
633 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
634 !(InstTemplate->getFriendObjectKind() &&
635 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000636 InstTemplate->setInstantiatedFromMemberTemplate(D);
637
638 // Add non-friends into the owner.
639 if (!InstTemplate->getFriendObjectKind())
640 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000641 return InstTemplate;
642}
643
Douglas Gregord475b8d2009-03-25 21:17:03 +0000644Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
645 CXXRecordDecl *PrevDecl = 0;
646 if (D->isInjectedClassName())
647 PrevDecl = cast<CXXRecordDecl>(Owner);
648
649 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000650 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000651 D->getLocation(), D->getIdentifier(),
652 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000653 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000654 // FIXME: Check against AS_none is an ugly hack to work around the issue that
655 // the tag decls introduced by friend class declarations don't have an access
656 // specifier. Remove once this area of the code gets sorted out.
657 if (D->getAccess() != AS_none)
658 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000659 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000660 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000661
John McCall02cace72009-08-28 07:59:38 +0000662 // If the original function was part of a friend declaration,
663 // inherit its namespace state.
664 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
665 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
666
Anders Carlssond8b285f2009-09-01 04:26:58 +0000667 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
668
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000669 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000670 return Record;
671}
672
John McCall02cace72009-08-28 07:59:38 +0000673/// Normal class members are of more specific types and therefore
674/// don't make it here. This function serves two purposes:
675/// 1) instantiating function templates
676/// 2) substituting friend declarations
677/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000678 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
679 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000680 // Check whether there is already a function template specialization for
681 // this declaration.
682 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
683 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000684 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000685 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000686 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000687 TemplateArgs.getInnermost().getFlatArgumentList(),
688 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000689 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000690
691 FunctionTemplateSpecializationInfo *Info
692 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000693 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Douglas Gregor127102b2009-06-29 20:59:39 +0000695 // If we already have a function template specialization, return it.
696 if (Info)
697 return Info->Function;
698 }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Douglas Gregor550d9b22009-10-31 17:21:17 +0000700 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Douglas Gregore53060f2009-06-25 22:08:12 +0000702 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000703 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000704 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000705 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000706
Douglas Gregore53060f2009-06-25 22:08:12 +0000707 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000708 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
709 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000710 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000711 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000712 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000713 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000714 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000715 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Douglas Gregore53060f2009-06-25 22:08:12 +0000717 // Attach the parameters
718 for (unsigned P = 0; P < Params.size(); ++P)
719 Params[P]->setOwningFunction(Function);
720 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000721
Douglas Gregora735b202009-10-13 14:39:41 +0000722 if (TemplateParams) {
723 // Our resulting instantiation is actually a function template, since we
724 // are substituting only the outer template parameters. For example, given
725 //
726 // template<typename T>
727 // struct X {
728 // template<typename U> friend void f(T, U);
729 // };
730 //
731 // X<int> x;
732 //
733 // We are instantiating the friend function template "f" within X<int>,
734 // which means substituting int for T, but leaving "f" as a friend function
735 // template.
736 // Build the function template itself.
737 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
738 Function->getLocation(),
739 Function->getDeclName(),
740 TemplateParams, Function);
741 Function->setDescribedFunctionTemplate(FunctionTemplate);
742 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000743 } else if (FunctionTemplate) {
744 // Record this function template specialization.
745 Function->setFunctionTemplateSpecialization(SemaRef.Context,
746 FunctionTemplate,
747 &TemplateArgs.getInnermost(),
748 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000749 }
Douglas Gregora735b202009-10-13 14:39:41 +0000750
Douglas Gregore53060f2009-06-25 22:08:12 +0000751 if (InitFunctionInstantiation(Function, D))
752 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Douglas Gregore53060f2009-06-25 22:08:12 +0000754 bool Redeclaration = false;
755 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000756
John McCall68263142009-11-18 22:49:29 +0000757 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
758 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
759
Douglas Gregora735b202009-10-13 14:39:41 +0000760 if (TemplateParams || !FunctionTemplate) {
761 // Look only into the namespace where the friend would be declared to
762 // find a previous declaration. This is the innermost enclosing namespace,
763 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000764 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000765
Douglas Gregora735b202009-10-13 14:39:41 +0000766 // In C++, the previous declaration we find might be a tag type
767 // (class or enum). In this case, the new declaration will hide the
768 // tag type. Note that this does does not apply if we're declaring a
769 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000770 if (Previous.isSingleTagDecl())
771 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000772 }
773
John McCall9f54ad42009-12-10 09:41:52 +0000774 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
775 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000776 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000777
Douglas Gregora735b202009-10-13 14:39:41 +0000778 // If the original function was part of a friend declaration,
779 // inherit its namespace state and add it to the owner.
780 NamedDecl *FromFriendD
781 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
782 if (FromFriendD->getFriendObjectKind()) {
783 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000784 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000785 if (TemplateParams) {
786 ToFriendD = cast<NamedDecl>(FunctionTemplate);
787 PrevDecl = FunctionTemplate->getPreviousDeclaration();
788 } else {
789 ToFriendD = Function;
790 PrevDecl = Function->getPreviousDeclaration();
791 }
792 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
793 if (!Owner->isDependentContext() && !PrevDecl)
794 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
795
796 if (!TemplateParams)
797 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
798 }
799
Douglas Gregore53060f2009-06-25 22:08:12 +0000800 return Function;
801}
802
Douglas Gregord60e1052009-08-27 16:57:43 +0000803Decl *
804TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
805 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000806 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
807 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000808 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000809 // We are creating a function template specialization from a function
810 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000811 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000812 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000813 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000814 TemplateArgs.getInnermost().getFlatArgumentList(),
815 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000816 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
818 FunctionTemplateSpecializationInfo *Info
819 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000820 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Douglas Gregor6b906862009-08-21 00:16:32 +0000822 // If we already have a function template specialization, return it.
823 if (Info)
824 return Info->Function;
825 }
826
Douglas Gregor550d9b22009-10-31 17:21:17 +0000827 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000828
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000829 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000830 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000831 if (T.isNull())
832 return 0;
833
834 // Build the instantiated method declaration.
835 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000836 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Douglas Gregordec06662009-08-21 18:42:58 +0000838 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000839 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000840 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
841 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
842 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000843 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
844 Constructor->getLocation(),
845 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000846 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000847 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000848 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000849 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
850 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
851 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
852 SemaRef.Context.getCanonicalType(ClassTy));
853 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
854 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000855 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000856 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000857 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000858 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000859 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000860 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
861 ConvTy);
862 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
863 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000864 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000865 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000866 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000867 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000868 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000869 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000870 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000871 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000872
Douglas Gregord60e1052009-08-27 16:57:43 +0000873 if (TemplateParams) {
874 // Our resulting instantiation is actually a function template, since we
875 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000876 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000877 // template<typename T>
878 // struct X {
879 // template<typename U> void f(T, U);
880 // };
881 //
882 // X<int> x;
883 //
884 // We are instantiating the member template "f" within X<int>, which means
885 // substituting int for T, but leaving "f" as a member function template.
886 // Build the function template itself.
887 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
888 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000889 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000890 TemplateParams, Method);
891 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000892 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000893 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000894 } else if (FunctionTemplate) {
895 // Record this function template specialization.
896 Method->setFunctionTemplateSpecialization(SemaRef.Context,
897 FunctionTemplate,
898 &TemplateArgs.getInnermost(),
899 InsertPos);
900 } else {
901 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000902 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000903 }
904
Mike Stump1eb44332009-09-09 15:08:12 +0000905 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000906 // out-of-line, the instantiation will have the same lexical
907 // context (which will be a namespace scope) as the template.
908 if (D->isOutOfLine())
909 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Douglas Gregor5545e162009-03-24 00:38:23 +0000911 // Attach the parameters
912 for (unsigned P = 0; P < Params.size(); ++P)
913 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000914 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000915
916 if (InitMethodInstantiation(Method, D))
917 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000918
John McCall68263142009-11-18 22:49:29 +0000919 LookupResult Previous(SemaRef, Name, SourceLocation(),
920 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Douglas Gregord60e1052009-08-27 16:57:43 +0000922 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000923 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Douglas Gregordec06662009-08-21 18:42:58 +0000925 // In C++, the previous declaration we find might be a tag type
926 // (class or enum). In this case, the new declaration will hide the
927 // tag type. Note that this does does not apply if we're declaring a
928 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000929 if (Previous.isSingleTagDecl())
930 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000931 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000932
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000933 bool Redeclaration = false;
934 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000935 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000936 /*FIXME:*/OverloadableAttrRequired);
937
Douglas Gregor4ba31362009-12-01 17:24:26 +0000938 if (D->isPure())
939 SemaRef.CheckPureMethod(Method, SourceRange());
940
John McCall68263142009-11-18 22:49:29 +0000941 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000942 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000943 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000945 return Method;
946}
947
Douglas Gregor615c5d42009-03-24 16:43:20 +0000948Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000949 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000950}
951
Douglas Gregor03b2b072009-03-24 00:15:49 +0000952Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000953 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000954}
955
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000956Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000957 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000958}
959
Douglas Gregor6477b692009-03-25 15:04:13 +0000960ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000961 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000962 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000963 if (DI) {
964 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
965 D->getDeclName());
966 if (DI) T = DI->getType();
967 } else {
968 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
969 D->getDeclName());
970 DI = 0;
971 }
972
973 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000974 return 0;
975
John McCall58e46772009-10-23 21:48:59 +0000976 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000977
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000978 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000979 ParmVarDecl *Param
980 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
981 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000982
Anders Carlsson9351c172009-08-25 03:18:48 +0000983 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000984 if (D->hasUninstantiatedDefaultArg())
985 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000986 else if (Expr *Arg = D->getDefaultArg())
987 Param->setUninstantiatedDefaultArg(Arg);
988
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000989 // Note: we don't try to instantiate function parameters until after
990 // we've instantiated the function's type. Therefore, we don't have
991 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000992 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000993 return Param;
994}
995
John McCalle29ba202009-08-20 01:44:21 +0000996Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
997 TemplateTypeParmDecl *D) {
998 // TODO: don't always clone when decls are refcounted.
999 const Type* T = D->getTypeForDecl();
1000 assert(T->isTemplateTypeParmType());
1001 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001002
John McCalle29ba202009-08-20 01:44:21 +00001003 TemplateTypeParmDecl *Inst =
1004 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001005 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001006 TTPT->getName(),
1007 D->wasDeclaredWithTypename(),
1008 D->isParameterPack());
1009
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001010 if (D->hasDefaultArgument())
1011 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001012
Douglas Gregor550d9b22009-10-31 17:21:17 +00001013 // Introduce this template parameter's instantiation into the instantiation
1014 // scope.
1015 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1016
John McCalle29ba202009-08-20 01:44:21 +00001017 return Inst;
1018}
1019
Douglas Gregor33642df2009-10-23 23:25:44 +00001020Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1021 NonTypeTemplateParmDecl *D) {
1022 // Substitute into the type of the non-type template parameter.
1023 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001024 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001025 if (DI) {
1026 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1027 D->getDeclName());
1028 if (DI) T = DI->getType();
1029 } else {
1030 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1031 D->getDeclName());
1032 DI = 0;
1033 }
1034 if (T.isNull())
1035 return 0;
1036
1037 // Check that this type is acceptable for a non-type template parameter.
1038 bool Invalid = false;
1039 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1040 if (T.isNull()) {
1041 T = SemaRef.Context.IntTy;
1042 Invalid = true;
1043 }
1044
1045 NonTypeTemplateParmDecl *Param
1046 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1047 D->getDepth() - 1, D->getPosition(),
1048 D->getIdentifier(), T, DI);
1049 if (Invalid)
1050 Param->setInvalidDecl();
1051
1052 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001053
1054 // Introduce this template parameter's instantiation into the instantiation
1055 // scope.
1056 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001057 return Param;
1058}
1059
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001060Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001061TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1062 TemplateTemplateParmDecl *D) {
1063 // Instantiate the template parameter list of the template template parameter.
1064 TemplateParameterList *TempParams = D->getTemplateParameters();
1065 TemplateParameterList *InstParams;
1066 {
1067 // Perform the actual substitution of template parameters within a new,
1068 // local instantiation scope.
1069 Sema::LocalInstantiationScope Scope(SemaRef);
1070 InstParams = SubstTemplateParams(TempParams);
1071 if (!InstParams)
1072 return NULL;
1073 }
1074
1075 // Build the template template parameter.
1076 TemplateTemplateParmDecl *Param
1077 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1078 D->getDepth() - 1, D->getPosition(),
1079 D->getIdentifier(), InstParams);
1080 Param->setDefaultArgument(D->getDefaultArgument());
1081
1082 // Introduce this template parameter's instantiation into the instantiation
1083 // scope.
1084 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1085
1086 return Param;
1087}
1088
Douglas Gregor48c32a72009-11-17 06:07:40 +00001089Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1090 // Using directives are never dependent, so they require no explicit
1091
1092 UsingDirectiveDecl *Inst
1093 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1094 D->getNamespaceKeyLocation(),
1095 D->getQualifierRange(), D->getQualifier(),
1096 D->getIdentLocation(),
1097 D->getNominatedNamespace(),
1098 D->getCommonAncestor());
1099 Owner->addDecl(Inst);
1100 return Inst;
1101}
1102
John McCalled976492009-12-04 22:46:56 +00001103Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1104 // The nested name specifier is non-dependent, so no transformation
1105 // is required.
1106
John McCall9f54ad42009-12-10 09:41:52 +00001107 // We only need to do redeclaration lookups if we're in a class
1108 // scope (in fact, it's not really even possible in non-class
1109 // scopes).
1110 bool CheckRedeclaration = Owner->isRecord();
1111
1112 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1113 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1114
John McCalled976492009-12-04 22:46:56 +00001115 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1116 D->getLocation(),
1117 D->getNestedNameRange(),
1118 D->getUsingLocation(),
1119 D->getTargetNestedNameDecl(),
1120 D->getDeclName(),
1121 D->isTypeName());
1122
1123 CXXScopeSpec SS;
1124 SS.setScopeRep(D->getTargetNestedNameDecl());
1125 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001126
1127 if (CheckRedeclaration) {
1128 Prev.setHideTags(false);
1129 SemaRef.LookupQualifiedName(Prev, Owner);
1130
1131 // Check for invalid redeclarations.
1132 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1133 D->isTypeName(), SS,
1134 D->getLocation(), Prev))
1135 NewUD->setInvalidDecl();
1136
1137 }
1138
1139 if (!NewUD->isInvalidDecl() &&
1140 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001141 D->getLocation()))
1142 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001143
John McCalled976492009-12-04 22:46:56 +00001144 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1145 NewUD->setAccess(D->getAccess());
1146 Owner->addDecl(NewUD);
1147
John McCall9f54ad42009-12-10 09:41:52 +00001148 // Don't process the shadow decls for an invalid decl.
1149 if (NewUD->isInvalidDecl())
1150 return NewUD;
1151
1152 // Process the shadow decls.
1153 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1154 I != E; ++I) {
1155 UsingShadowDecl *Shadow = *I;
1156 NamedDecl *InstTarget =
1157 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1158 TemplateArgs));
1159
1160 if (CheckRedeclaration &&
1161 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1162 continue;
1163
1164 UsingShadowDecl *InstShadow
1165 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1166 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1167 }
John McCalled976492009-12-04 22:46:56 +00001168
1169 return NewUD;
1170}
1171
1172Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001173 // Ignore these; we handle them in bulk when processing the UsingDecl.
1174 return 0;
John McCalled976492009-12-04 22:46:56 +00001175}
1176
John McCall7ba107a2009-11-18 02:36:19 +00001177Decl * TemplateDeclInstantiator
1178 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001179 NestedNameSpecifier *NNS =
1180 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1181 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001182 TemplateArgs);
1183 if (!NNS)
1184 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001186 CXXScopeSpec SS;
1187 SS.setRange(D->getTargetNestedNameRange());
1188 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
1190 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001191 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001192 D->getUsingLoc(), SS, D->getLocation(),
1193 D->getDeclName(), 0,
1194 /*instantiation*/ true,
1195 /*typename*/ true, D->getTypenameLoc());
1196 if (UD)
John McCalled976492009-12-04 22:46:56 +00001197 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1198
John McCall7ba107a2009-11-18 02:36:19 +00001199 return UD;
1200}
1201
1202Decl * TemplateDeclInstantiator
1203 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1204 NestedNameSpecifier *NNS =
1205 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1206 D->getTargetNestedNameRange(),
1207 TemplateArgs);
1208 if (!NNS)
1209 return 0;
1210
1211 CXXScopeSpec SS;
1212 SS.setRange(D->getTargetNestedNameRange());
1213 SS.setScopeRep(NNS);
1214
1215 NamedDecl *UD =
1216 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1217 D->getUsingLoc(), SS, D->getLocation(),
1218 D->getDeclName(), 0,
1219 /*instantiation*/ true,
1220 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001221 if (UD)
John McCalled976492009-12-04 22:46:56 +00001222 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1223
Anders Carlsson0d8df782009-08-29 19:37:28 +00001224 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001225}
1226
John McCallce3ff2b2009-08-25 22:02:44 +00001227Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001228 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001229 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001230 return Instantiator.Visit(D);
1231}
1232
John McCalle29ba202009-08-20 01:44:21 +00001233/// \brief Instantiates a nested template parameter list in the current
1234/// instantiation context.
1235///
1236/// \param L The parameter list to instantiate
1237///
1238/// \returns NULL if there was an error
1239TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001240TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001241 // Get errors for all the parameters before bailing out.
1242 bool Invalid = false;
1243
1244 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001245 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001246 ParamVector Params;
1247 Params.reserve(N);
1248 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1249 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001250 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001251 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001252 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001253 }
1254
1255 // Clean up if we had an error.
1256 if (Invalid) {
1257 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1258 PI != PE; ++PI)
1259 if (*PI)
1260 (*PI)->Destroy(SemaRef.Context);
1261 return NULL;
1262 }
1263
1264 TemplateParameterList *InstL
1265 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1266 L->getLAngleLoc(), &Params.front(), N,
1267 L->getRAngleLoc());
1268 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001269}
John McCalle29ba202009-08-20 01:44:21 +00001270
Douglas Gregored9c0f92009-10-29 00:04:11 +00001271/// \brief Instantiate the declaration of a class template partial
1272/// specialization.
1273///
1274/// \param ClassTemplate the (instantiated) class template that is partially
1275// specialized by the instantiation of \p PartialSpec.
1276///
1277/// \param PartialSpec the (uninstantiated) class template partial
1278/// specialization that we are instantiating.
1279///
1280/// \returns true if there was an error, false otherwise.
1281bool
1282TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1283 ClassTemplateDecl *ClassTemplate,
1284 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001285 // Create a local instantiation scope for this class template partial
1286 // specialization, which will contain the instantiations of the template
1287 // parameters.
1288 Sema::LocalInstantiationScope Scope(SemaRef);
1289
Douglas Gregored9c0f92009-10-29 00:04:11 +00001290 // Substitute into the template parameters of the class template partial
1291 // specialization.
1292 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1293 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1294 if (!InstParams)
1295 return true;
1296
1297 // Substitute into the template arguments of the class template partial
1298 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001299 const TemplateArgumentLoc *PartialSpecTemplateArgs
1300 = PartialSpec->getTemplateArgsAsWritten();
1301 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1302
John McCalld5532b62009-11-23 01:53:49 +00001303 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001304 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001305 TemplateArgumentLoc Loc;
1306 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001307 return true;
John McCalld5532b62009-11-23 01:53:49 +00001308 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001309 }
1310
1311
1312 // Check that the template argument list is well-formed for this
1313 // class template.
1314 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1315 InstTemplateArgs.size());
1316 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1317 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001318 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001319 false,
1320 Converted))
1321 return true;
1322
1323 // Figure out where to insert this class template partial specialization
1324 // in the member template's set of class template partial specializations.
1325 llvm::FoldingSetNodeID ID;
1326 ClassTemplatePartialSpecializationDecl::Profile(ID,
1327 Converted.getFlatArguments(),
1328 Converted.flatSize(),
1329 SemaRef.Context);
1330 void *InsertPos = 0;
1331 ClassTemplateSpecializationDecl *PrevDecl
1332 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1333 InsertPos);
1334
1335 // Build the canonical type that describes the converted template
1336 // arguments of the class template partial specialization.
1337 QualType CanonType
1338 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1339 Converted.getFlatArguments(),
1340 Converted.flatSize());
1341
1342 // Build the fully-sugared type for this class template
1343 // specialization as the user wrote in the specialization
1344 // itself. This means that we'll pretty-print the type retrieved
1345 // from the specialization's declaration the way that the user
1346 // actually wrote the specialization, rather than formatting the
1347 // name based on the "canonical" representation used to store the
1348 // template arguments in the specialization.
1349 QualType WrittenTy
1350 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001351 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001352 CanonType);
1353
1354 if (PrevDecl) {
1355 // We've already seen a partial specialization with the same template
1356 // parameters and template arguments. This can happen, for example, when
1357 // substituting the outer template arguments ends up causing two
1358 // class template partial specializations of a member class template
1359 // to have identical forms, e.g.,
1360 //
1361 // template<typename T, typename U>
1362 // struct Outer {
1363 // template<typename X, typename Y> struct Inner;
1364 // template<typename Y> struct Inner<T, Y>;
1365 // template<typename Y> struct Inner<U, Y>;
1366 // };
1367 //
1368 // Outer<int, int> outer; // error: the partial specializations of Inner
1369 // // have the same signature.
1370 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1371 << WrittenTy;
1372 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1373 << SemaRef.Context.getTypeDeclType(PrevDecl);
1374 return true;
1375 }
1376
1377
1378 // Create the class template partial specialization declaration.
1379 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1380 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1381 PartialSpec->getLocation(),
1382 InstParams,
1383 ClassTemplate,
1384 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001385 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001386 0);
1387 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1388 InstPartialSpec->setTypeAsWritten(WrittenTy);
1389
1390 // Add this partial specialization to the set of class template partial
1391 // specializations.
1392 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1393 InsertPos);
1394 return false;
1395}
1396
John McCallce3ff2b2009-08-25 22:02:44 +00001397/// \brief Does substitution on the type of the given function, including
1398/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001399///
John McCallce3ff2b2009-08-25 22:02:44 +00001400/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001401///
1402/// \param Params the instantiated parameter declarations
1403
John McCallce3ff2b2009-08-25 22:02:44 +00001404/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001405/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001406QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001407TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001408 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1409 bool InvalidDecl = false;
1410
John McCallce3ff2b2009-08-25 22:02:44 +00001411 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001412 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001413 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001414 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001415 PEnd = D->param_end();
1416 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001417 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001418 if (PInst->getType()->isVoidType()) {
1419 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1420 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001421 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001422 PInst->getType(),
1423 diag::err_abstract_type_in_decl,
1424 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001425 PInst->setInvalidDecl();
1426
1427 Params.push_back(PInst);
1428 ParamTys.push_back(PInst->getType());
1429
1430 if (PInst->isInvalidDecl())
1431 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001432 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001433 InvalidDecl = true;
1434 }
1435
1436 // FIXME: Deallocate dead declarations.
1437 if (InvalidDecl)
1438 return QualType();
1439
John McCall183700f2009-09-21 23:43:11 +00001440 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001441 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001442 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001443 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1444 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001445 if (ResultType.isNull())
1446 return QualType();
1447
Jay Foadbeaaccd2009-05-21 09:52:38 +00001448 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001449 Proto->isVariadic(), Proto->getTypeQuals(),
1450 D->getLocation(), D->getDeclName());
1451}
1452
Mike Stump1eb44332009-09-09 15:08:12 +00001453/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001454/// declaration (New) from the corresponding fields of its template (Tmpl).
1455///
1456/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001457bool
1458TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001459 FunctionDecl *Tmpl) {
1460 if (Tmpl->isDeleted())
1461 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Douglas Gregorcca9e962009-07-01 22:01:06 +00001463 // If we are performing substituting explicitly-specified template arguments
1464 // or deduced template arguments into a function template and we reach this
1465 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001466 // to keeping the new function template specialization. We therefore
1467 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001468 // into a template instantiation for this specific function template
1469 // specialization, which is not a SFINAE context, so that we diagnose any
1470 // further errors in the declaration itself.
1471 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1472 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1473 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1474 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001475 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001476 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001478 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001479 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001480 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1481 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001482 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001483 }
1484 }
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001486 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1487 assert(Proto && "Function template without prototype?");
1488
1489 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1490 Proto->getNoReturnAttr()) {
1491 // The function has an exception specification or a "noreturn"
1492 // attribute. Substitute into each of the exception types.
1493 llvm::SmallVector<QualType, 4> Exceptions;
1494 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1495 // FIXME: Poor location information!
1496 QualType T
1497 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1498 New->getLocation(), New->getDeclName());
1499 if (T.isNull() ||
1500 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1501 continue;
1502
1503 Exceptions.push_back(T);
1504 }
1505
1506 // Rebuild the function type
1507
1508 const FunctionProtoType *NewProto
1509 = New->getType()->getAs<FunctionProtoType>();
1510 assert(NewProto && "Template instantiation without function prototype?");
1511 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1512 NewProto->arg_type_begin(),
1513 NewProto->getNumArgs(),
1514 NewProto->isVariadic(),
1515 NewProto->getTypeQuals(),
1516 Proto->hasExceptionSpec(),
1517 Proto->hasAnyExceptionSpec(),
1518 Exceptions.size(),
1519 Exceptions.data(),
1520 Proto->getNoReturnAttr()));
1521 }
1522
Douglas Gregore53060f2009-06-25 22:08:12 +00001523 return false;
1524}
1525
Douglas Gregor5545e162009-03-24 00:38:23 +00001526/// \brief Initializes common fields of an instantiated method
1527/// declaration (New) from the corresponding fields of its template
1528/// (Tmpl).
1529///
1530/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001531bool
1532TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001533 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001534 if (InitFunctionInstantiation(New, Tmpl))
1535 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Douglas Gregor5545e162009-03-24 00:38:23 +00001537 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1538 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001539 if (Tmpl->isVirtualAsWritten())
1540 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001541
1542 // FIXME: attributes
1543 // FIXME: New needs a pointer to Tmpl
1544 return false;
1545}
Douglas Gregora58861f2009-05-13 20:28:22 +00001546
1547/// \brief Instantiate the definition of the given function from its
1548/// template.
1549///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001550/// \param PointOfInstantiation the point at which the instantiation was
1551/// required. Note that this is not precisely a "point of instantiation"
1552/// for the function, but it's close.
1553///
Douglas Gregora58861f2009-05-13 20:28:22 +00001554/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001555/// function template specialization or member function of a class template
1556/// specialization.
1557///
1558/// \param Recursive if true, recursively instantiates any functions that
1559/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001560///
1561/// \param DefinitionRequired if true, then we are performing an explicit
1562/// instantiation where the body of the function is required. Complain if
1563/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001564void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001565 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001566 bool Recursive,
1567 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001568 if (Function->isInvalidDecl())
1569 return;
1570
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001571 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001573 // Never instantiate an explicit specialization.
1574 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1575 return;
1576
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001577 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001578 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001579 Stmt *Pattern = 0;
1580 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001581 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001582
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001583 if (!Pattern) {
1584 if (DefinitionRequired) {
1585 if (Function->getPrimaryTemplate())
1586 Diag(PointOfInstantiation,
1587 diag::err_explicit_instantiation_undefined_func_template)
1588 << Function->getPrimaryTemplate();
1589 else
1590 Diag(PointOfInstantiation,
1591 diag::err_explicit_instantiation_undefined_member)
1592 << 1 << Function->getDeclName() << Function->getDeclContext();
1593
1594 if (PatternDecl)
1595 Diag(PatternDecl->getLocation(),
1596 diag::note_explicit_instantiation_here);
1597 }
1598
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001599 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001600 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001601
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001602 // C++0x [temp.explicit]p9:
1603 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001604 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001605 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001606 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001607 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001608 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001609 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001611 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1612 if (Inst)
1613 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001614
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001615 // If we're performing recursive template instantiation, create our own
1616 // queue of pending implicit instantiations that we will instantiate later,
1617 // while we're still within our own instantiation context.
1618 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1619 if (Recursive)
1620 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001622 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1623
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001624 // Introduce a new scope where local variable instantiations will be
1625 // recorded.
1626 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001628 // Introduce the instantiated function parameters into the local
1629 // instantiation scope.
1630 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1631 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1632 Function->getParamDecl(I));
1633
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001634 // Enter the scope of this instantiation. We don't use
1635 // PushDeclContext because we don't have a scope.
1636 DeclContext *PreviousContext = CurContext;
1637 CurContext = Function;
1638
Mike Stump1eb44332009-09-09 15:08:12 +00001639 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001640 getTemplateInstantiationArgs(Function);
1641
1642 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001643 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001644 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1645 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1646 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001647 }
1648
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001649 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001650 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001651
Douglas Gregor52604ab2009-09-11 21:19:12 +00001652 if (Body.isInvalid())
1653 Function->setInvalidDecl();
1654
Mike Stump1eb44332009-09-09 15:08:12 +00001655 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001656 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001657
1658 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001659
1660 DeclGroupRef DG(Function);
1661 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001663 if (Recursive) {
1664 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001665 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001666 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001668 // Restore the set of pending implicit instantiations.
1669 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1670 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001671}
1672
1673/// \brief Instantiate the definition of the given variable from its
1674/// template.
1675///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001676/// \param PointOfInstantiation the point at which the instantiation was
1677/// required. Note that this is not precisely a "point of instantiation"
1678/// for the function, but it's close.
1679///
1680/// \param Var the already-instantiated declaration of a static member
1681/// variable of a class template specialization.
1682///
1683/// \param Recursive if true, recursively instantiates any functions that
1684/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001685///
1686/// \param DefinitionRequired if true, then we are performing an explicit
1687/// instantiation where an out-of-line definition of the member variable
1688/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001689void Sema::InstantiateStaticDataMemberDefinition(
1690 SourceLocation PointOfInstantiation,
1691 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001692 bool Recursive,
1693 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001694 if (Var->isInvalidDecl())
1695 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Douglas Gregor7caa6822009-07-24 20:34:43 +00001697 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001698 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001699 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001700 assert(Def->isStaticDataMember() && "Not a static data member?");
1701 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor0d035142009-10-27 18:42:08 +00001703 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001704 // We did not find an out-of-line definition of this static data member,
1705 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001706 // instantiate this definition (or provide a specialization for it) in
1707 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001708 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001709 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001710 Diag(PointOfInstantiation,
1711 diag::err_explicit_instantiation_undefined_member)
1712 << 2 << Var->getDeclName() << Var->getDeclContext();
1713 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1714 }
1715
Douglas Gregor7caa6822009-07-24 20:34:43 +00001716 return;
1717 }
1718
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001719 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001720 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001721 return;
1722
1723 // C++0x [temp.explicit]p9:
1724 // Except for inline functions, other explicit instantiation declarations
1725 // have the effect of suppressing the implicit instantiation of the entity
1726 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001727 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001728 == TSK_ExplicitInstantiationDeclaration)
1729 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Douglas Gregor7caa6822009-07-24 20:34:43 +00001731 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1732 if (Inst)
1733 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Douglas Gregor7caa6822009-07-24 20:34:43 +00001735 // If we're performing recursive template instantiation, create our own
1736 // queue of pending implicit instantiations that we will instantiate later,
1737 // while we're still within our own instantiation context.
1738 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1739 if (Recursive)
1740 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Douglas Gregor7caa6822009-07-24 20:34:43 +00001742 // Enter the scope of this instantiation. We don't use
1743 // PushDeclContext because we don't have a scope.
1744 DeclContext *PreviousContext = CurContext;
1745 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001747 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001748 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001749 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001750 CurContext = PreviousContext;
1751
1752 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001753 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001754 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1755 assert(MSInfo && "Missing member specialization information?");
1756 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1757 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001758 DeclGroupRef DG(Var);
1759 Consumer.HandleTopLevelDecl(DG);
1760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor7caa6822009-07-24 20:34:43 +00001762 if (Recursive) {
1763 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001764 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001765 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Douglas Gregor7caa6822009-07-24 20:34:43 +00001767 // Restore the set of pending implicit instantiations.
1768 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001769 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001770}
Douglas Gregor815215d2009-05-27 05:35:12 +00001771
Anders Carlsson09025312009-08-29 05:16:22 +00001772void
1773Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1774 const CXXConstructorDecl *Tmpl,
1775 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Anders Carlsson09025312009-08-29 05:16:22 +00001777 llvm::SmallVector<MemInitTy*, 4> NewInits;
1778
1779 // Instantiate all the initializers.
1780 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001781 InitsEnd = Tmpl->init_end();
1782 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001783 CXXBaseOrMemberInitializer *Init = *Inits;
1784
1785 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Anders Carlsson09025312009-08-29 05:16:22 +00001787 // Instantiate all the arguments.
1788 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1789 Args != ArgsEnd; ++Args) {
1790 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1791
1792 if (NewArg.isInvalid())
1793 New->setInvalidDecl();
1794 else
1795 NewArgs.push_back(NewArg.takeAs<Expr>());
1796 }
1797
1798 MemInitResult NewInit;
1799
1800 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001801 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001802 TemplateArgs,
1803 Init->getSourceLocation(),
1804 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001805 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001806 New->setInvalidDecl();
1807 continue;
1808 }
1809
John McCalla93c9342009-12-07 02:54:59 +00001810 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001811 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001812 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001813 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001814 Init->getRParenLoc(),
1815 New->getParent());
1816 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001817 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001819 // Is this an anonymous union?
1820 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001821 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001822 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001823 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1824 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001825
1826 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001827 NewArgs.size(),
1828 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001829 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001830 Init->getRParenLoc());
1831 }
1832
1833 if (NewInit.isInvalid())
1834 New->setInvalidDecl();
1835 else {
1836 // FIXME: It would be nice if ASTOwningVector had a release function.
1837 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Anders Carlsson09025312009-08-29 05:16:22 +00001839 NewInits.push_back((MemInitTy *)NewInit.get());
1840 }
1841 }
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Anders Carlsson09025312009-08-29 05:16:22 +00001843 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001844 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001845 /*FIXME: ColonLoc */
1846 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001847 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001848}
1849
John McCall52a575a2009-08-29 08:11:13 +00001850// TODO: this could be templated if the various decl types used the
1851// same method name.
1852static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1853 ClassTemplateDecl *Instance) {
1854 Pattern = Pattern->getCanonicalDecl();
1855
1856 do {
1857 Instance = Instance->getCanonicalDecl();
1858 if (Pattern == Instance) return true;
1859 Instance = Instance->getInstantiatedFromMemberTemplate();
1860 } while (Instance);
1861
1862 return false;
1863}
1864
Douglas Gregor0d696532009-09-28 06:34:35 +00001865static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1866 FunctionTemplateDecl *Instance) {
1867 Pattern = Pattern->getCanonicalDecl();
1868
1869 do {
1870 Instance = Instance->getCanonicalDecl();
1871 if (Pattern == Instance) return true;
1872 Instance = Instance->getInstantiatedFromMemberTemplate();
1873 } while (Instance);
1874
1875 return false;
1876}
1877
Douglas Gregored9c0f92009-10-29 00:04:11 +00001878static bool
1879isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1880 ClassTemplatePartialSpecializationDecl *Instance) {
1881 Pattern
1882 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1883 do {
1884 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1885 Instance->getCanonicalDecl());
1886 if (Pattern == Instance)
1887 return true;
1888 Instance = Instance->getInstantiatedFromMember();
1889 } while (Instance);
1890
1891 return false;
1892}
1893
John McCall52a575a2009-08-29 08:11:13 +00001894static bool isInstantiationOf(CXXRecordDecl *Pattern,
1895 CXXRecordDecl *Instance) {
1896 Pattern = Pattern->getCanonicalDecl();
1897
1898 do {
1899 Instance = Instance->getCanonicalDecl();
1900 if (Pattern == Instance) return true;
1901 Instance = Instance->getInstantiatedFromMemberClass();
1902 } while (Instance);
1903
1904 return false;
1905}
1906
1907static bool isInstantiationOf(FunctionDecl *Pattern,
1908 FunctionDecl *Instance) {
1909 Pattern = Pattern->getCanonicalDecl();
1910
1911 do {
1912 Instance = Instance->getCanonicalDecl();
1913 if (Pattern == Instance) return true;
1914 Instance = Instance->getInstantiatedFromMemberFunction();
1915 } while (Instance);
1916
1917 return false;
1918}
1919
1920static bool isInstantiationOf(EnumDecl *Pattern,
1921 EnumDecl *Instance) {
1922 Pattern = Pattern->getCanonicalDecl();
1923
1924 do {
1925 Instance = Instance->getCanonicalDecl();
1926 if (Pattern == Instance) return true;
1927 Instance = Instance->getInstantiatedFromMemberEnum();
1928 } while (Instance);
1929
1930 return false;
1931}
1932
John McCalled976492009-12-04 22:46:56 +00001933static bool isInstantiationOf(UsingShadowDecl *Pattern,
1934 UsingShadowDecl *Instance,
1935 ASTContext &C) {
1936 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1937}
1938
1939static bool isInstantiationOf(UsingDecl *Pattern,
1940 UsingDecl *Instance,
1941 ASTContext &C) {
1942 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1943}
1944
John McCall7ba107a2009-11-18 02:36:19 +00001945static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1946 UsingDecl *Instance,
1947 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001948 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001949}
1950
1951static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001952 UsingDecl *Instance,
1953 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001954 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001955}
1956
John McCall52a575a2009-08-29 08:11:13 +00001957static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1958 VarDecl *Instance) {
1959 assert(Instance->isStaticDataMember());
1960
1961 Pattern = Pattern->getCanonicalDecl();
1962
1963 do {
1964 Instance = Instance->getCanonicalDecl();
1965 if (Pattern == Instance) return true;
1966 Instance = Instance->getInstantiatedFromStaticDataMember();
1967 } while (Instance);
1968
1969 return false;
1970}
1971
John McCalled976492009-12-04 22:46:56 +00001972// Other is the prospective instantiation
1973// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001974static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001975 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001976 if (UnresolvedUsingTypenameDecl *UUD
1977 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1978 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1979 return isInstantiationOf(UUD, UD, Ctx);
1980 }
1981 }
1982
1983 if (UnresolvedUsingValueDecl *UUD
1984 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001985 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1986 return isInstantiationOf(UUD, UD, Ctx);
1987 }
1988 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001989
Anders Carlsson0d8df782009-08-29 19:37:28 +00001990 return false;
1991 }
Mike Stump1eb44332009-09-09 15:08:12 +00001992
John McCall52a575a2009-08-29 08:11:13 +00001993 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1994 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001995
John McCall52a575a2009-08-29 08:11:13 +00001996 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1997 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001998
John McCall52a575a2009-08-29 08:11:13 +00001999 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2000 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002001
Douglas Gregor7caa6822009-07-24 20:34:43 +00002002 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002003 if (Var->isStaticDataMember())
2004 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2005
2006 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2007 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002008
Douglas Gregor0d696532009-09-28 06:34:35 +00002009 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2010 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2011
Douglas Gregored9c0f92009-10-29 00:04:11 +00002012 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2013 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2014 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2015 PartialSpec);
2016
Anders Carlssond8b285f2009-09-01 04:26:58 +00002017 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2018 if (!Field->getDeclName()) {
2019 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002020 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002021 cast<FieldDecl>(D);
2022 }
2023 }
Mike Stump1eb44332009-09-09 15:08:12 +00002024
John McCalled976492009-12-04 22:46:56 +00002025 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2026 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2027
2028 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2029 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2030
Douglas Gregor815215d2009-05-27 05:35:12 +00002031 return D->getDeclName() && isa<NamedDecl>(Other) &&
2032 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2033}
2034
2035template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002036static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002037 NamedDecl *D,
2038 ForwardIterator first,
2039 ForwardIterator last) {
2040 for (; first != last; ++first)
2041 if (isInstantiationOf(Ctx, D, *first))
2042 return cast<NamedDecl>(*first);
2043
2044 return 0;
2045}
2046
John McCall02cace72009-08-28 07:59:38 +00002047/// \brief Finds the instantiation of the given declaration context
2048/// within the current instantiation.
2049///
2050/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002051DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2052 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002053 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002054 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002055 return cast_or_null<DeclContext>(ID);
2056 } else return DC;
2057}
2058
Douglas Gregored961e72009-05-27 17:54:46 +00002059/// \brief Find the instantiation of the given declaration within the
2060/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002061///
2062/// This routine is intended to be used when \p D is a declaration
2063/// referenced from within a template, that needs to mapped into the
2064/// corresponding declaration within an instantiation. For example,
2065/// given:
2066///
2067/// \code
2068/// template<typename T>
2069/// struct X {
2070/// enum Kind {
2071/// KnownValue = sizeof(T)
2072/// };
2073///
2074/// bool getKind() const { return KnownValue; }
2075/// };
2076///
2077/// template struct X<int>;
2078/// \endcode
2079///
2080/// In the instantiation of X<int>::getKind(), we need to map the
2081/// EnumConstantDecl for KnownValue (which refers to
2082/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002083/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2084/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002085NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2086 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002087 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002088 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2089 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2090 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002091 // D is a local of some kind. Look into the map of local
2092 // declarations to their instantiations.
2093 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2094 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002095
Douglas Gregore95b4092009-09-16 18:34:49 +00002096 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2097 if (!Record->isDependentContext())
2098 return D;
2099
2100 // If the RecordDecl is actually the injected-class-name or a "templated"
2101 // declaration for a class template or class template partial
2102 // specialization, substitute into the injected-class-name of the
2103 // class template or partial specialization to find the new DeclContext.
2104 QualType T;
2105 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2106
2107 if (ClassTemplate) {
2108 T = ClassTemplate->getInjectedClassNameType(Context);
2109 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2110 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2111 T = Context.getTypeDeclType(Record);
2112 ClassTemplate = PartialSpec->getSpecializedTemplate();
2113 }
2114
2115 if (!T.isNull()) {
2116 // Substitute into the injected-class-name to get the type corresponding
2117 // to the instantiation we want. This substitution should never fail,
2118 // since we know we can instantiate the injected-class-name or we wouldn't
2119 // have gotten to the injected-class-name!
2120 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2121 // instantiation in the common case?
2122 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2123 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2124
2125 if (!T->isDependentType()) {
2126 assert(T->isRecordType() && "Instantiation must produce a record type");
2127 return T->getAs<RecordType>()->getDecl();
2128 }
2129
2130 // We are performing "partial" template instantiation to create the
2131 // member declarations for the members of a class template
2132 // specialization. Therefore, D is actually referring to something in
2133 // the current instantiation. Look through the current context,
2134 // which contains actual instantiations, to find the instantiation of
2135 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002136 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002137 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002138 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002139 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002140 if (isInstantiationOf(ClassTemplate,
2141 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002142 return Spec;
2143 }
2144
Mike Stump1eb44332009-09-09 15:08:12 +00002145 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002146 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002147 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002148 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002149
2150 // Fall through to deal with other dependent record types (e.g.,
2151 // anonymous unions in class templates).
2152 }
John McCall52a575a2009-08-29 08:11:13 +00002153
Douglas Gregore95b4092009-09-16 18:34:49 +00002154 if (!ParentDC->isDependentContext())
2155 return D;
2156
2157 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002158 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002159 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Douglas Gregor815215d2009-05-27 05:35:12 +00002161 if (ParentDC != D->getDeclContext()) {
2162 // We performed some kind of instantiation in the parent context,
2163 // so now we need to look into the instantiated parent context to
2164 // find the instantiation of the declaration D.
2165 NamedDecl *Result = 0;
2166 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002167 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002168 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2169 } else {
2170 // Since we don't have a name for the entity we're looking for,
2171 // our only option is to walk through all of the declarations to
2172 // find that name. This will occur in a few cases:
2173 //
2174 // - anonymous struct/union within a template
2175 // - unnamed class/struct/union/enum within a template
2176 //
2177 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002178 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002179 ParentDC->decls_begin(),
2180 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002181 }
Mike Stump1eb44332009-09-09 15:08:12 +00002182
John McCall9f54ad42009-12-10 09:41:52 +00002183 // UsingShadowDecls can instantiate to nothing because of using hiding.
2184 assert((Result || isa<UsingShadowDecl>(D))
2185 && "Unable to find instantiation of declaration!");
2186
Douglas Gregor815215d2009-05-27 05:35:12 +00002187 D = Result;
2188 }
2189
Douglas Gregor815215d2009-05-27 05:35:12 +00002190 return D;
2191}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002192
Mike Stump1eb44332009-09-09 15:08:12 +00002193/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002194/// instantiations we have seen until this point.
2195void Sema::PerformPendingImplicitInstantiations() {
2196 while (!PendingImplicitInstantiations.empty()) {
2197 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002198 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Douglas Gregor7caa6822009-07-24 20:34:43 +00002200 // Instantiate function definitions
2201 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002202 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002203 Function->getLocation(), *this,
2204 Context.getSourceManager(),
2205 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002207 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002208 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002209 continue;
2210 }
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregor7caa6822009-07-24 20:34:43 +00002212 // Instantiate static data member definitions.
2213 VarDecl *Var = cast<VarDecl>(Inst.first);
2214 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002215
Mike Stump1eb44332009-09-09 15:08:12 +00002216 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002217 Var->getLocation(), *this,
2218 Context.getSourceManager(),
2219 "instantiating static data member "
2220 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Douglas Gregor7caa6822009-07-24 20:34:43 +00002222 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002223 }
2224}