blob: 9c4c38a134a999805a11b88b637e84a70ea500f7 [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!");
630 if (!InstTemplate->getInstantiatedFromMemberTemplate())
631 InstTemplate->setInstantiatedFromMemberTemplate(D);
632
633 // Add non-friends into the owner.
634 if (!InstTemplate->getFriendObjectKind())
635 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000636 return InstTemplate;
637}
638
Douglas Gregord475b8d2009-03-25 21:17:03 +0000639Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
640 CXXRecordDecl *PrevDecl = 0;
641 if (D->isInjectedClassName())
642 PrevDecl = cast<CXXRecordDecl>(Owner);
643
644 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000645 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000646 D->getLocation(), D->getIdentifier(),
647 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000648 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000649 // FIXME: Check against AS_none is an ugly hack to work around the issue that
650 // the tag decls introduced by friend class declarations don't have an access
651 // specifier. Remove once this area of the code gets sorted out.
652 if (D->getAccess() != AS_none)
653 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000654 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000655 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000656
John McCall02cace72009-08-28 07:59:38 +0000657 // If the original function was part of a friend declaration,
658 // inherit its namespace state.
659 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
660 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
661
Anders Carlssond8b285f2009-09-01 04:26:58 +0000662 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
663
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000664 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000665 return Record;
666}
667
John McCall02cace72009-08-28 07:59:38 +0000668/// Normal class members are of more specific types and therefore
669/// don't make it here. This function serves two purposes:
670/// 1) instantiating function templates
671/// 2) substituting friend declarations
672/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000673 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
674 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000675 // Check whether there is already a function template specialization for
676 // this declaration.
677 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
678 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000679 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000680 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000681 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000682 TemplateArgs.getInnermost().getFlatArgumentList(),
683 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000684 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000685
686 FunctionTemplateSpecializationInfo *Info
687 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000688 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Douglas Gregor127102b2009-06-29 20:59:39 +0000690 // If we already have a function template specialization, return it.
691 if (Info)
692 return Info->Function;
693 }
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Douglas Gregor550d9b22009-10-31 17:21:17 +0000695 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Douglas Gregore53060f2009-06-25 22:08:12 +0000697 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000698 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000699 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000700 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000701
Douglas Gregore53060f2009-06-25 22:08:12 +0000702 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000703 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
704 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000705 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000706 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000707 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000708 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000709 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000710 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Douglas Gregore53060f2009-06-25 22:08:12 +0000712 // Attach the parameters
713 for (unsigned P = 0; P < Params.size(); ++P)
714 Params[P]->setOwningFunction(Function);
715 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000716
Douglas Gregora735b202009-10-13 14:39:41 +0000717 if (TemplateParams) {
718 // Our resulting instantiation is actually a function template, since we
719 // are substituting only the outer template parameters. For example, given
720 //
721 // template<typename T>
722 // struct X {
723 // template<typename U> friend void f(T, U);
724 // };
725 //
726 // X<int> x;
727 //
728 // We are instantiating the friend function template "f" within X<int>,
729 // which means substituting int for T, but leaving "f" as a friend function
730 // template.
731 // Build the function template itself.
732 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
733 Function->getLocation(),
734 Function->getDeclName(),
735 TemplateParams, Function);
736 Function->setDescribedFunctionTemplate(FunctionTemplate);
737 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000738 } else if (FunctionTemplate) {
739 // Record this function template specialization.
740 Function->setFunctionTemplateSpecialization(SemaRef.Context,
741 FunctionTemplate,
742 &TemplateArgs.getInnermost(),
743 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000744 }
Douglas Gregora735b202009-10-13 14:39:41 +0000745
Douglas Gregore53060f2009-06-25 22:08:12 +0000746 if (InitFunctionInstantiation(Function, D))
747 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Douglas Gregore53060f2009-06-25 22:08:12 +0000749 bool Redeclaration = false;
750 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000751
John McCall68263142009-11-18 22:49:29 +0000752 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
753 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
754
Douglas Gregora735b202009-10-13 14:39:41 +0000755 if (TemplateParams || !FunctionTemplate) {
756 // Look only into the namespace where the friend would be declared to
757 // find a previous declaration. This is the innermost enclosing namespace,
758 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000759 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000760
Douglas Gregora735b202009-10-13 14:39:41 +0000761 // In C++, the previous declaration we find might be a tag type
762 // (class or enum). In this case, the new declaration will hide the
763 // tag type. Note that this does does not apply if we're declaring a
764 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000765 if (Previous.isSingleTagDecl())
766 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000767 }
768
John McCall9f54ad42009-12-10 09:41:52 +0000769 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
770 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000771 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000772
Douglas Gregora735b202009-10-13 14:39:41 +0000773 // If the original function was part of a friend declaration,
774 // inherit its namespace state and add it to the owner.
775 NamedDecl *FromFriendD
776 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
777 if (FromFriendD->getFriendObjectKind()) {
778 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000779 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000780 if (TemplateParams) {
781 ToFriendD = cast<NamedDecl>(FunctionTemplate);
782 PrevDecl = FunctionTemplate->getPreviousDeclaration();
783 } else {
784 ToFriendD = Function;
785 PrevDecl = Function->getPreviousDeclaration();
786 }
787 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
788 if (!Owner->isDependentContext() && !PrevDecl)
789 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
790
791 if (!TemplateParams)
792 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
793 }
794
Douglas Gregore53060f2009-06-25 22:08:12 +0000795 return Function;
796}
797
Douglas Gregord60e1052009-08-27 16:57:43 +0000798Decl *
799TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
800 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000801 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
802 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000803 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000804 // We are creating a function template specialization from a function
805 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000806 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000807 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000808 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000809 TemplateArgs.getInnermost().getFlatArgumentList(),
810 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000811 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000812
813 FunctionTemplateSpecializationInfo *Info
814 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000815 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Douglas Gregor6b906862009-08-21 00:16:32 +0000817 // If we already have a function template specialization, return it.
818 if (Info)
819 return Info->Function;
820 }
821
Douglas Gregor550d9b22009-10-31 17:21:17 +0000822 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000823
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000824 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000825 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000826 if (T.isNull())
827 return 0;
828
829 // Build the instantiated method declaration.
830 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000831 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Douglas Gregordec06662009-08-21 18:42:58 +0000833 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000834 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000835 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
836 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
837 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000838 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
839 Constructor->getLocation(),
840 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000841 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000842 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000843 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000844 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
845 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
846 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
847 SemaRef.Context.getCanonicalType(ClassTy));
848 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
849 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000850 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000851 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000852 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000853 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000854 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000855 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
856 ConvTy);
857 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
858 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000859 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000860 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000861 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000862 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000863 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000864 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000865 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000866 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000867
Douglas Gregord60e1052009-08-27 16:57:43 +0000868 if (TemplateParams) {
869 // Our resulting instantiation is actually a function template, since we
870 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000871 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000872 // template<typename T>
873 // struct X {
874 // template<typename U> void f(T, U);
875 // };
876 //
877 // X<int> x;
878 //
879 // We are instantiating the member template "f" within X<int>, which means
880 // substituting int for T, but leaving "f" as a member function template.
881 // Build the function template itself.
882 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
883 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000884 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000885 TemplateParams, Method);
886 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000887 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000888 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000889 } else if (FunctionTemplate) {
890 // Record this function template specialization.
891 Method->setFunctionTemplateSpecialization(SemaRef.Context,
892 FunctionTemplate,
893 &TemplateArgs.getInnermost(),
894 InsertPos);
895 } else {
896 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000897 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000898 }
899
Mike Stump1eb44332009-09-09 15:08:12 +0000900 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000901 // out-of-line, the instantiation will have the same lexical
902 // context (which will be a namespace scope) as the template.
903 if (D->isOutOfLine())
904 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregor5545e162009-03-24 00:38:23 +0000906 // Attach the parameters
907 for (unsigned P = 0; P < Params.size(); ++P)
908 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000909 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000910
911 if (InitMethodInstantiation(Method, D))
912 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000913
John McCall68263142009-11-18 22:49:29 +0000914 LookupResult Previous(SemaRef, Name, SourceLocation(),
915 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Douglas Gregord60e1052009-08-27 16:57:43 +0000917 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000918 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Douglas Gregordec06662009-08-21 18:42:58 +0000920 // In C++, the previous declaration we find might be a tag type
921 // (class or enum). In this case, the new declaration will hide the
922 // tag type. Note that this does does not apply if we're declaring a
923 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000924 if (Previous.isSingleTagDecl())
925 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000926 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000927
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000928 bool Redeclaration = false;
929 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000930 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000931 /*FIXME:*/OverloadableAttrRequired);
932
Douglas Gregor4ba31362009-12-01 17:24:26 +0000933 if (D->isPure())
934 SemaRef.CheckPureMethod(Method, SourceRange());
935
John McCall68263142009-11-18 22:49:29 +0000936 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000937 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000938 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000940 return Method;
941}
942
Douglas Gregor615c5d42009-03-24 16:43:20 +0000943Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000944 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000945}
946
Douglas Gregor03b2b072009-03-24 00:15:49 +0000947Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000948 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000949}
950
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000951Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000952 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000953}
954
Douglas Gregor6477b692009-03-25 15:04:13 +0000955ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000956 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000957 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000958 if (DI) {
959 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
960 D->getDeclName());
961 if (DI) T = DI->getType();
962 } else {
963 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
964 D->getDeclName());
965 DI = 0;
966 }
967
968 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000969 return 0;
970
John McCall58e46772009-10-23 21:48:59 +0000971 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000972
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000973 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000974 ParmVarDecl *Param
975 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
976 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000977
Anders Carlsson9351c172009-08-25 03:18:48 +0000978 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000979 if (D->hasUninstantiatedDefaultArg())
980 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000981 else if (Expr *Arg = D->getDefaultArg())
982 Param->setUninstantiatedDefaultArg(Arg);
983
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000984 // Note: we don't try to instantiate function parameters until after
985 // we've instantiated the function's type. Therefore, we don't have
986 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000987 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000988 return Param;
989}
990
John McCalle29ba202009-08-20 01:44:21 +0000991Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
992 TemplateTypeParmDecl *D) {
993 // TODO: don't always clone when decls are refcounted.
994 const Type* T = D->getTypeForDecl();
995 assert(T->isTemplateTypeParmType());
996 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000997
John McCalle29ba202009-08-20 01:44:21 +0000998 TemplateTypeParmDecl *Inst =
999 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001000 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001001 TTPT->getName(),
1002 D->wasDeclaredWithTypename(),
1003 D->isParameterPack());
1004
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001005 if (D->hasDefaultArgument())
1006 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001007
Douglas Gregor550d9b22009-10-31 17:21:17 +00001008 // Introduce this template parameter's instantiation into the instantiation
1009 // scope.
1010 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1011
John McCalle29ba202009-08-20 01:44:21 +00001012 return Inst;
1013}
1014
Douglas Gregor33642df2009-10-23 23:25:44 +00001015Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1016 NonTypeTemplateParmDecl *D) {
1017 // Substitute into the type of the non-type template parameter.
1018 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001019 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001020 if (DI) {
1021 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1022 D->getDeclName());
1023 if (DI) T = DI->getType();
1024 } else {
1025 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1026 D->getDeclName());
1027 DI = 0;
1028 }
1029 if (T.isNull())
1030 return 0;
1031
1032 // Check that this type is acceptable for a non-type template parameter.
1033 bool Invalid = false;
1034 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1035 if (T.isNull()) {
1036 T = SemaRef.Context.IntTy;
1037 Invalid = true;
1038 }
1039
1040 NonTypeTemplateParmDecl *Param
1041 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1042 D->getDepth() - 1, D->getPosition(),
1043 D->getIdentifier(), T, DI);
1044 if (Invalid)
1045 Param->setInvalidDecl();
1046
1047 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001048
1049 // Introduce this template parameter's instantiation into the instantiation
1050 // scope.
1051 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001052 return Param;
1053}
1054
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001055Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001056TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1057 TemplateTemplateParmDecl *D) {
1058 // Instantiate the template parameter list of the template template parameter.
1059 TemplateParameterList *TempParams = D->getTemplateParameters();
1060 TemplateParameterList *InstParams;
1061 {
1062 // Perform the actual substitution of template parameters within a new,
1063 // local instantiation scope.
1064 Sema::LocalInstantiationScope Scope(SemaRef);
1065 InstParams = SubstTemplateParams(TempParams);
1066 if (!InstParams)
1067 return NULL;
1068 }
1069
1070 // Build the template template parameter.
1071 TemplateTemplateParmDecl *Param
1072 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1073 D->getDepth() - 1, D->getPosition(),
1074 D->getIdentifier(), InstParams);
1075 Param->setDefaultArgument(D->getDefaultArgument());
1076
1077 // Introduce this template parameter's instantiation into the instantiation
1078 // scope.
1079 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1080
1081 return Param;
1082}
1083
Douglas Gregor48c32a72009-11-17 06:07:40 +00001084Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1085 // Using directives are never dependent, so they require no explicit
1086
1087 UsingDirectiveDecl *Inst
1088 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1089 D->getNamespaceKeyLocation(),
1090 D->getQualifierRange(), D->getQualifier(),
1091 D->getIdentLocation(),
1092 D->getNominatedNamespace(),
1093 D->getCommonAncestor());
1094 Owner->addDecl(Inst);
1095 return Inst;
1096}
1097
John McCalled976492009-12-04 22:46:56 +00001098Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1099 // The nested name specifier is non-dependent, so no transformation
1100 // is required.
1101
John McCall9f54ad42009-12-10 09:41:52 +00001102 // We only need to do redeclaration lookups if we're in a class
1103 // scope (in fact, it's not really even possible in non-class
1104 // scopes).
1105 bool CheckRedeclaration = Owner->isRecord();
1106
1107 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1108 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1109
John McCalled976492009-12-04 22:46:56 +00001110 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1111 D->getLocation(),
1112 D->getNestedNameRange(),
1113 D->getUsingLocation(),
1114 D->getTargetNestedNameDecl(),
1115 D->getDeclName(),
1116 D->isTypeName());
1117
1118 CXXScopeSpec SS;
1119 SS.setScopeRep(D->getTargetNestedNameDecl());
1120 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001121
1122 if (CheckRedeclaration) {
1123 Prev.setHideTags(false);
1124 SemaRef.LookupQualifiedName(Prev, Owner);
1125
1126 // Check for invalid redeclarations.
1127 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1128 D->isTypeName(), SS,
1129 D->getLocation(), Prev))
1130 NewUD->setInvalidDecl();
1131
1132 }
1133
1134 if (!NewUD->isInvalidDecl() &&
1135 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001136 D->getLocation()))
1137 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001138
John McCalled976492009-12-04 22:46:56 +00001139 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1140 NewUD->setAccess(D->getAccess());
1141 Owner->addDecl(NewUD);
1142
John McCall9f54ad42009-12-10 09:41:52 +00001143 // Don't process the shadow decls for an invalid decl.
1144 if (NewUD->isInvalidDecl())
1145 return NewUD;
1146
1147 // Process the shadow decls.
1148 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1149 I != E; ++I) {
1150 UsingShadowDecl *Shadow = *I;
1151 NamedDecl *InstTarget =
1152 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1153 TemplateArgs));
1154
1155 if (CheckRedeclaration &&
1156 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1157 continue;
1158
1159 UsingShadowDecl *InstShadow
1160 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1161 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1162 }
John McCalled976492009-12-04 22:46:56 +00001163
1164 return NewUD;
1165}
1166
1167Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001168 // Ignore these; we handle them in bulk when processing the UsingDecl.
1169 return 0;
John McCalled976492009-12-04 22:46:56 +00001170}
1171
John McCall7ba107a2009-11-18 02:36:19 +00001172Decl * TemplateDeclInstantiator
1173 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001174 NestedNameSpecifier *NNS =
1175 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1176 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001177 TemplateArgs);
1178 if (!NNS)
1179 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001181 CXXScopeSpec SS;
1182 SS.setRange(D->getTargetNestedNameRange());
1183 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001184
1185 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001186 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001187 D->getUsingLoc(), SS, D->getLocation(),
1188 D->getDeclName(), 0,
1189 /*instantiation*/ true,
1190 /*typename*/ true, D->getTypenameLoc());
1191 if (UD)
John McCalled976492009-12-04 22:46:56 +00001192 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1193
John McCall7ba107a2009-11-18 02:36:19 +00001194 return UD;
1195}
1196
1197Decl * TemplateDeclInstantiator
1198 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1199 NestedNameSpecifier *NNS =
1200 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1201 D->getTargetNestedNameRange(),
1202 TemplateArgs);
1203 if (!NNS)
1204 return 0;
1205
1206 CXXScopeSpec SS;
1207 SS.setRange(D->getTargetNestedNameRange());
1208 SS.setScopeRep(NNS);
1209
1210 NamedDecl *UD =
1211 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1212 D->getUsingLoc(), SS, D->getLocation(),
1213 D->getDeclName(), 0,
1214 /*instantiation*/ true,
1215 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001216 if (UD)
John McCalled976492009-12-04 22:46:56 +00001217 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1218
Anders Carlsson0d8df782009-08-29 19:37:28 +00001219 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001220}
1221
John McCallce3ff2b2009-08-25 22:02:44 +00001222Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001223 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001224 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001225 return Instantiator.Visit(D);
1226}
1227
John McCalle29ba202009-08-20 01:44:21 +00001228/// \brief Instantiates a nested template parameter list in the current
1229/// instantiation context.
1230///
1231/// \param L The parameter list to instantiate
1232///
1233/// \returns NULL if there was an error
1234TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001235TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001236 // Get errors for all the parameters before bailing out.
1237 bool Invalid = false;
1238
1239 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001240 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001241 ParamVector Params;
1242 Params.reserve(N);
1243 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1244 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001245 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001246 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001247 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001248 }
1249
1250 // Clean up if we had an error.
1251 if (Invalid) {
1252 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1253 PI != PE; ++PI)
1254 if (*PI)
1255 (*PI)->Destroy(SemaRef.Context);
1256 return NULL;
1257 }
1258
1259 TemplateParameterList *InstL
1260 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1261 L->getLAngleLoc(), &Params.front(), N,
1262 L->getRAngleLoc());
1263 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001264}
John McCalle29ba202009-08-20 01:44:21 +00001265
Douglas Gregored9c0f92009-10-29 00:04:11 +00001266/// \brief Instantiate the declaration of a class template partial
1267/// specialization.
1268///
1269/// \param ClassTemplate the (instantiated) class template that is partially
1270// specialized by the instantiation of \p PartialSpec.
1271///
1272/// \param PartialSpec the (uninstantiated) class template partial
1273/// specialization that we are instantiating.
1274///
1275/// \returns true if there was an error, false otherwise.
1276bool
1277TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1278 ClassTemplateDecl *ClassTemplate,
1279 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001280 // Create a local instantiation scope for this class template partial
1281 // specialization, which will contain the instantiations of the template
1282 // parameters.
1283 Sema::LocalInstantiationScope Scope(SemaRef);
1284
Douglas Gregored9c0f92009-10-29 00:04:11 +00001285 // Substitute into the template parameters of the class template partial
1286 // specialization.
1287 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1288 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1289 if (!InstParams)
1290 return true;
1291
1292 // Substitute into the template arguments of the class template partial
1293 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001294 const TemplateArgumentLoc *PartialSpecTemplateArgs
1295 = PartialSpec->getTemplateArgsAsWritten();
1296 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1297
John McCalld5532b62009-11-23 01:53:49 +00001298 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001299 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001300 TemplateArgumentLoc Loc;
1301 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001302 return true;
John McCalld5532b62009-11-23 01:53:49 +00001303 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001304 }
1305
1306
1307 // Check that the template argument list is well-formed for this
1308 // class template.
1309 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1310 InstTemplateArgs.size());
1311 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1312 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001313 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001314 false,
1315 Converted))
1316 return true;
1317
1318 // Figure out where to insert this class template partial specialization
1319 // in the member template's set of class template partial specializations.
1320 llvm::FoldingSetNodeID ID;
1321 ClassTemplatePartialSpecializationDecl::Profile(ID,
1322 Converted.getFlatArguments(),
1323 Converted.flatSize(),
1324 SemaRef.Context);
1325 void *InsertPos = 0;
1326 ClassTemplateSpecializationDecl *PrevDecl
1327 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1328 InsertPos);
1329
1330 // Build the canonical type that describes the converted template
1331 // arguments of the class template partial specialization.
1332 QualType CanonType
1333 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1334 Converted.getFlatArguments(),
1335 Converted.flatSize());
1336
1337 // Build the fully-sugared type for this class template
1338 // specialization as the user wrote in the specialization
1339 // itself. This means that we'll pretty-print the type retrieved
1340 // from the specialization's declaration the way that the user
1341 // actually wrote the specialization, rather than formatting the
1342 // name based on the "canonical" representation used to store the
1343 // template arguments in the specialization.
1344 QualType WrittenTy
1345 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001346 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001347 CanonType);
1348
1349 if (PrevDecl) {
1350 // We've already seen a partial specialization with the same template
1351 // parameters and template arguments. This can happen, for example, when
1352 // substituting the outer template arguments ends up causing two
1353 // class template partial specializations of a member class template
1354 // to have identical forms, e.g.,
1355 //
1356 // template<typename T, typename U>
1357 // struct Outer {
1358 // template<typename X, typename Y> struct Inner;
1359 // template<typename Y> struct Inner<T, Y>;
1360 // template<typename Y> struct Inner<U, Y>;
1361 // };
1362 //
1363 // Outer<int, int> outer; // error: the partial specializations of Inner
1364 // // have the same signature.
1365 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1366 << WrittenTy;
1367 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1368 << SemaRef.Context.getTypeDeclType(PrevDecl);
1369 return true;
1370 }
1371
1372
1373 // Create the class template partial specialization declaration.
1374 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1375 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1376 PartialSpec->getLocation(),
1377 InstParams,
1378 ClassTemplate,
1379 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001380 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001381 0);
1382 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1383 InstPartialSpec->setTypeAsWritten(WrittenTy);
1384
1385 // Add this partial specialization to the set of class template partial
1386 // specializations.
1387 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1388 InsertPos);
1389 return false;
1390}
1391
John McCallce3ff2b2009-08-25 22:02:44 +00001392/// \brief Does substitution on the type of the given function, including
1393/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001394///
John McCallce3ff2b2009-08-25 22:02:44 +00001395/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001396///
1397/// \param Params the instantiated parameter declarations
1398
John McCallce3ff2b2009-08-25 22:02:44 +00001399/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001400/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001401QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001402TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001403 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1404 bool InvalidDecl = false;
1405
John McCallce3ff2b2009-08-25 22:02:44 +00001406 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001407 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001408 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001409 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001410 PEnd = D->param_end();
1411 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001412 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001413 if (PInst->getType()->isVoidType()) {
1414 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1415 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001416 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001417 PInst->getType(),
1418 diag::err_abstract_type_in_decl,
1419 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001420 PInst->setInvalidDecl();
1421
1422 Params.push_back(PInst);
1423 ParamTys.push_back(PInst->getType());
1424
1425 if (PInst->isInvalidDecl())
1426 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001427 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001428 InvalidDecl = true;
1429 }
1430
1431 // FIXME: Deallocate dead declarations.
1432 if (InvalidDecl)
1433 return QualType();
1434
John McCall183700f2009-09-21 23:43:11 +00001435 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001436 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001437 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001438 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1439 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001440 if (ResultType.isNull())
1441 return QualType();
1442
Jay Foadbeaaccd2009-05-21 09:52:38 +00001443 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001444 Proto->isVariadic(), Proto->getTypeQuals(),
1445 D->getLocation(), D->getDeclName());
1446}
1447
Mike Stump1eb44332009-09-09 15:08:12 +00001448/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001449/// declaration (New) from the corresponding fields of its template (Tmpl).
1450///
1451/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001452bool
1453TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001454 FunctionDecl *Tmpl) {
1455 if (Tmpl->isDeleted())
1456 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Douglas Gregorcca9e962009-07-01 22:01:06 +00001458 // If we are performing substituting explicitly-specified template arguments
1459 // or deduced template arguments into a function template and we reach this
1460 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001461 // to keeping the new function template specialization. We therefore
1462 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001463 // into a template instantiation for this specific function template
1464 // specialization, which is not a SFINAE context, so that we diagnose any
1465 // further errors in the declaration itself.
1466 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1467 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1468 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1469 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001470 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001471 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001472 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001473 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001474 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001475 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1476 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001477 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001478 }
1479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001481 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1482 assert(Proto && "Function template without prototype?");
1483
1484 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1485 Proto->getNoReturnAttr()) {
1486 // The function has an exception specification or a "noreturn"
1487 // attribute. Substitute into each of the exception types.
1488 llvm::SmallVector<QualType, 4> Exceptions;
1489 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1490 // FIXME: Poor location information!
1491 QualType T
1492 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1493 New->getLocation(), New->getDeclName());
1494 if (T.isNull() ||
1495 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1496 continue;
1497
1498 Exceptions.push_back(T);
1499 }
1500
1501 // Rebuild the function type
1502
1503 const FunctionProtoType *NewProto
1504 = New->getType()->getAs<FunctionProtoType>();
1505 assert(NewProto && "Template instantiation without function prototype?");
1506 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1507 NewProto->arg_type_begin(),
1508 NewProto->getNumArgs(),
1509 NewProto->isVariadic(),
1510 NewProto->getTypeQuals(),
1511 Proto->hasExceptionSpec(),
1512 Proto->hasAnyExceptionSpec(),
1513 Exceptions.size(),
1514 Exceptions.data(),
1515 Proto->getNoReturnAttr()));
1516 }
1517
Douglas Gregore53060f2009-06-25 22:08:12 +00001518 return false;
1519}
1520
Douglas Gregor5545e162009-03-24 00:38:23 +00001521/// \brief Initializes common fields of an instantiated method
1522/// declaration (New) from the corresponding fields of its template
1523/// (Tmpl).
1524///
1525/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001526bool
1527TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001528 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001529 if (InitFunctionInstantiation(New, Tmpl))
1530 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Douglas Gregor5545e162009-03-24 00:38:23 +00001532 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1533 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001534 if (Tmpl->isVirtualAsWritten())
1535 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001536
1537 // FIXME: attributes
1538 // FIXME: New needs a pointer to Tmpl
1539 return false;
1540}
Douglas Gregora58861f2009-05-13 20:28:22 +00001541
1542/// \brief Instantiate the definition of the given function from its
1543/// template.
1544///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001545/// \param PointOfInstantiation the point at which the instantiation was
1546/// required. Note that this is not precisely a "point of instantiation"
1547/// for the function, but it's close.
1548///
Douglas Gregora58861f2009-05-13 20:28:22 +00001549/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001550/// function template specialization or member function of a class template
1551/// specialization.
1552///
1553/// \param Recursive if true, recursively instantiates any functions that
1554/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001555///
1556/// \param DefinitionRequired if true, then we are performing an explicit
1557/// instantiation where the body of the function is required. Complain if
1558/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001559void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001560 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001561 bool Recursive,
1562 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001563 if (Function->isInvalidDecl())
1564 return;
1565
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001566 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001568 // Never instantiate an explicit specialization.
1569 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1570 return;
1571
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001572 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001573 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001574 Stmt *Pattern = 0;
1575 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001576 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001577
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001578 if (!Pattern) {
1579 if (DefinitionRequired) {
1580 if (Function->getPrimaryTemplate())
1581 Diag(PointOfInstantiation,
1582 diag::err_explicit_instantiation_undefined_func_template)
1583 << Function->getPrimaryTemplate();
1584 else
1585 Diag(PointOfInstantiation,
1586 diag::err_explicit_instantiation_undefined_member)
1587 << 1 << Function->getDeclName() << Function->getDeclContext();
1588
1589 if (PatternDecl)
1590 Diag(PatternDecl->getLocation(),
1591 diag::note_explicit_instantiation_here);
1592 }
1593
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001594 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001595 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001596
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001597 // C++0x [temp.explicit]p9:
1598 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001599 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001600 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001601 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001602 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001603 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001604 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001606 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1607 if (Inst)
1608 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001609
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001610 // If we're performing recursive template instantiation, create our own
1611 // queue of pending implicit instantiations that we will instantiate later,
1612 // while we're still within our own instantiation context.
1613 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1614 if (Recursive)
1615 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001617 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1618
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001619 // Introduce a new scope where local variable instantiations will be
1620 // recorded.
1621 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001623 // Introduce the instantiated function parameters into the local
1624 // instantiation scope.
1625 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1626 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1627 Function->getParamDecl(I));
1628
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001629 // Enter the scope of this instantiation. We don't use
1630 // PushDeclContext because we don't have a scope.
1631 DeclContext *PreviousContext = CurContext;
1632 CurContext = Function;
1633
Mike Stump1eb44332009-09-09 15:08:12 +00001634 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001635 getTemplateInstantiationArgs(Function);
1636
1637 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001638 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001639 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1640 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1641 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001642 }
1643
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001644 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001645 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001646
Douglas Gregor52604ab2009-09-11 21:19:12 +00001647 if (Body.isInvalid())
1648 Function->setInvalidDecl();
1649
Mike Stump1eb44332009-09-09 15:08:12 +00001650 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001651 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001652
1653 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001654
1655 DeclGroupRef DG(Function);
1656 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001658 if (Recursive) {
1659 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001660 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001661 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001663 // Restore the set of pending implicit instantiations.
1664 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1665 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001666}
1667
1668/// \brief Instantiate the definition of the given variable from its
1669/// template.
1670///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001671/// \param PointOfInstantiation the point at which the instantiation was
1672/// required. Note that this is not precisely a "point of instantiation"
1673/// for the function, but it's close.
1674///
1675/// \param Var the already-instantiated declaration of a static member
1676/// variable of a class template specialization.
1677///
1678/// \param Recursive if true, recursively instantiates any functions that
1679/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001680///
1681/// \param DefinitionRequired if true, then we are performing an explicit
1682/// instantiation where an out-of-line definition of the member variable
1683/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001684void Sema::InstantiateStaticDataMemberDefinition(
1685 SourceLocation PointOfInstantiation,
1686 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001687 bool Recursive,
1688 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001689 if (Var->isInvalidDecl())
1690 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Douglas Gregor7caa6822009-07-24 20:34:43 +00001692 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001693 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001694 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001695 assert(Def->isStaticDataMember() && "Not a static data member?");
1696 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Douglas Gregor0d035142009-10-27 18:42:08 +00001698 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001699 // We did not find an out-of-line definition of this static data member,
1700 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001701 // instantiate this definition (or provide a specialization for it) in
1702 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001703 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001704 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001705 Diag(PointOfInstantiation,
1706 diag::err_explicit_instantiation_undefined_member)
1707 << 2 << Var->getDeclName() << Var->getDeclContext();
1708 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1709 }
1710
Douglas Gregor7caa6822009-07-24 20:34:43 +00001711 return;
1712 }
1713
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001714 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001715 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001716 return;
1717
1718 // C++0x [temp.explicit]p9:
1719 // Except for inline functions, other explicit instantiation declarations
1720 // have the effect of suppressing the implicit instantiation of the entity
1721 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001722 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001723 == TSK_ExplicitInstantiationDeclaration)
1724 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Douglas Gregor7caa6822009-07-24 20:34:43 +00001726 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1727 if (Inst)
1728 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Douglas Gregor7caa6822009-07-24 20:34:43 +00001730 // If we're performing recursive template instantiation, create our own
1731 // queue of pending implicit instantiations that we will instantiate later,
1732 // while we're still within our own instantiation context.
1733 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1734 if (Recursive)
1735 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Douglas Gregor7caa6822009-07-24 20:34:43 +00001737 // Enter the scope of this instantiation. We don't use
1738 // PushDeclContext because we don't have a scope.
1739 DeclContext *PreviousContext = CurContext;
1740 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001742 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001743 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001744 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001745 CurContext = PreviousContext;
1746
1747 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001748 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001749 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1750 assert(MSInfo && "Missing member specialization information?");
1751 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1752 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001753 DeclGroupRef DG(Var);
1754 Consumer.HandleTopLevelDecl(DG);
1755 }
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregor7caa6822009-07-24 20:34:43 +00001757 if (Recursive) {
1758 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001759 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001760 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor7caa6822009-07-24 20:34:43 +00001762 // Restore the set of pending implicit instantiations.
1763 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001764 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001765}
Douglas Gregor815215d2009-05-27 05:35:12 +00001766
Anders Carlsson09025312009-08-29 05:16:22 +00001767void
1768Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1769 const CXXConstructorDecl *Tmpl,
1770 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Anders Carlsson09025312009-08-29 05:16:22 +00001772 llvm::SmallVector<MemInitTy*, 4> NewInits;
1773
1774 // Instantiate all the initializers.
1775 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001776 InitsEnd = Tmpl->init_end();
1777 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001778 CXXBaseOrMemberInitializer *Init = *Inits;
1779
1780 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Anders Carlsson09025312009-08-29 05:16:22 +00001782 // Instantiate all the arguments.
1783 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1784 Args != ArgsEnd; ++Args) {
1785 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1786
1787 if (NewArg.isInvalid())
1788 New->setInvalidDecl();
1789 else
1790 NewArgs.push_back(NewArg.takeAs<Expr>());
1791 }
1792
1793 MemInitResult NewInit;
1794
1795 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001796 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001797 TemplateArgs,
1798 Init->getSourceLocation(),
1799 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001800 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001801 New->setInvalidDecl();
1802 continue;
1803 }
1804
John McCalla93c9342009-12-07 02:54:59 +00001805 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001806 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001807 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001808 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001809 Init->getRParenLoc(),
1810 New->getParent());
1811 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001812 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001814 // Is this an anonymous union?
1815 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001816 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001817 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001818 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1819 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001820
1821 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001822 NewArgs.size(),
1823 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001824 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001825 Init->getRParenLoc());
1826 }
1827
1828 if (NewInit.isInvalid())
1829 New->setInvalidDecl();
1830 else {
1831 // FIXME: It would be nice if ASTOwningVector had a release function.
1832 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Anders Carlsson09025312009-08-29 05:16:22 +00001834 NewInits.push_back((MemInitTy *)NewInit.get());
1835 }
1836 }
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Anders Carlsson09025312009-08-29 05:16:22 +00001838 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001839 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001840 /*FIXME: ColonLoc */
1841 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001842 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001843}
1844
John McCall52a575a2009-08-29 08:11:13 +00001845// TODO: this could be templated if the various decl types used the
1846// same method name.
1847static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1848 ClassTemplateDecl *Instance) {
1849 Pattern = Pattern->getCanonicalDecl();
1850
1851 do {
1852 Instance = Instance->getCanonicalDecl();
1853 if (Pattern == Instance) return true;
1854 Instance = Instance->getInstantiatedFromMemberTemplate();
1855 } while (Instance);
1856
1857 return false;
1858}
1859
Douglas Gregor0d696532009-09-28 06:34:35 +00001860static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1861 FunctionTemplateDecl *Instance) {
1862 Pattern = Pattern->getCanonicalDecl();
1863
1864 do {
1865 Instance = Instance->getCanonicalDecl();
1866 if (Pattern == Instance) return true;
1867 Instance = Instance->getInstantiatedFromMemberTemplate();
1868 } while (Instance);
1869
1870 return false;
1871}
1872
Douglas Gregored9c0f92009-10-29 00:04:11 +00001873static bool
1874isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1875 ClassTemplatePartialSpecializationDecl *Instance) {
1876 Pattern
1877 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1878 do {
1879 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1880 Instance->getCanonicalDecl());
1881 if (Pattern == Instance)
1882 return true;
1883 Instance = Instance->getInstantiatedFromMember();
1884 } while (Instance);
1885
1886 return false;
1887}
1888
John McCall52a575a2009-08-29 08:11:13 +00001889static bool isInstantiationOf(CXXRecordDecl *Pattern,
1890 CXXRecordDecl *Instance) {
1891 Pattern = Pattern->getCanonicalDecl();
1892
1893 do {
1894 Instance = Instance->getCanonicalDecl();
1895 if (Pattern == Instance) return true;
1896 Instance = Instance->getInstantiatedFromMemberClass();
1897 } while (Instance);
1898
1899 return false;
1900}
1901
1902static bool isInstantiationOf(FunctionDecl *Pattern,
1903 FunctionDecl *Instance) {
1904 Pattern = Pattern->getCanonicalDecl();
1905
1906 do {
1907 Instance = Instance->getCanonicalDecl();
1908 if (Pattern == Instance) return true;
1909 Instance = Instance->getInstantiatedFromMemberFunction();
1910 } while (Instance);
1911
1912 return false;
1913}
1914
1915static bool isInstantiationOf(EnumDecl *Pattern,
1916 EnumDecl *Instance) {
1917 Pattern = Pattern->getCanonicalDecl();
1918
1919 do {
1920 Instance = Instance->getCanonicalDecl();
1921 if (Pattern == Instance) return true;
1922 Instance = Instance->getInstantiatedFromMemberEnum();
1923 } while (Instance);
1924
1925 return false;
1926}
1927
John McCalled976492009-12-04 22:46:56 +00001928static bool isInstantiationOf(UsingShadowDecl *Pattern,
1929 UsingShadowDecl *Instance,
1930 ASTContext &C) {
1931 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1932}
1933
1934static bool isInstantiationOf(UsingDecl *Pattern,
1935 UsingDecl *Instance,
1936 ASTContext &C) {
1937 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1938}
1939
John McCall7ba107a2009-11-18 02:36:19 +00001940static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1941 UsingDecl *Instance,
1942 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001943 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001944}
1945
1946static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001947 UsingDecl *Instance,
1948 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001949 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001950}
1951
John McCall52a575a2009-08-29 08:11:13 +00001952static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1953 VarDecl *Instance) {
1954 assert(Instance->isStaticDataMember());
1955
1956 Pattern = Pattern->getCanonicalDecl();
1957
1958 do {
1959 Instance = Instance->getCanonicalDecl();
1960 if (Pattern == Instance) return true;
1961 Instance = Instance->getInstantiatedFromStaticDataMember();
1962 } while (Instance);
1963
1964 return false;
1965}
1966
John McCalled976492009-12-04 22:46:56 +00001967// Other is the prospective instantiation
1968// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001969static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001970 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001971 if (UnresolvedUsingTypenameDecl *UUD
1972 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1973 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1974 return isInstantiationOf(UUD, UD, Ctx);
1975 }
1976 }
1977
1978 if (UnresolvedUsingValueDecl *UUD
1979 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001980 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1981 return isInstantiationOf(UUD, UD, Ctx);
1982 }
1983 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001984
Anders Carlsson0d8df782009-08-29 19:37:28 +00001985 return false;
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
John McCall52a575a2009-08-29 08:11:13 +00001988 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1989 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001990
John McCall52a575a2009-08-29 08:11:13 +00001991 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1992 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001993
John McCall52a575a2009-08-29 08:11:13 +00001994 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1995 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001996
Douglas Gregor7caa6822009-07-24 20:34:43 +00001997 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001998 if (Var->isStaticDataMember())
1999 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2000
2001 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2002 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002003
Douglas Gregor0d696532009-09-28 06:34:35 +00002004 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2005 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2006
Douglas Gregored9c0f92009-10-29 00:04:11 +00002007 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2008 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2009 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2010 PartialSpec);
2011
Anders Carlssond8b285f2009-09-01 04:26:58 +00002012 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2013 if (!Field->getDeclName()) {
2014 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002015 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002016 cast<FieldDecl>(D);
2017 }
2018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019
John McCalled976492009-12-04 22:46:56 +00002020 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2021 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2022
2023 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2024 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2025
Douglas Gregor815215d2009-05-27 05:35:12 +00002026 return D->getDeclName() && isa<NamedDecl>(Other) &&
2027 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2028}
2029
2030template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002031static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002032 NamedDecl *D,
2033 ForwardIterator first,
2034 ForwardIterator last) {
2035 for (; first != last; ++first)
2036 if (isInstantiationOf(Ctx, D, *first))
2037 return cast<NamedDecl>(*first);
2038
2039 return 0;
2040}
2041
John McCall02cace72009-08-28 07:59:38 +00002042/// \brief Finds the instantiation of the given declaration context
2043/// within the current instantiation.
2044///
2045/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002046DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2047 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002048 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002049 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002050 return cast_or_null<DeclContext>(ID);
2051 } else return DC;
2052}
2053
Douglas Gregored961e72009-05-27 17:54:46 +00002054/// \brief Find the instantiation of the given declaration within the
2055/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002056///
2057/// This routine is intended to be used when \p D is a declaration
2058/// referenced from within a template, that needs to mapped into the
2059/// corresponding declaration within an instantiation. For example,
2060/// given:
2061///
2062/// \code
2063/// template<typename T>
2064/// struct X {
2065/// enum Kind {
2066/// KnownValue = sizeof(T)
2067/// };
2068///
2069/// bool getKind() const { return KnownValue; }
2070/// };
2071///
2072/// template struct X<int>;
2073/// \endcode
2074///
2075/// In the instantiation of X<int>::getKind(), we need to map the
2076/// EnumConstantDecl for KnownValue (which refers to
2077/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002078/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2079/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002080NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2081 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002082 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002083 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2084 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2085 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002086 // D is a local of some kind. Look into the map of local
2087 // declarations to their instantiations.
2088 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2089 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002090
Douglas Gregore95b4092009-09-16 18:34:49 +00002091 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2092 if (!Record->isDependentContext())
2093 return D;
2094
2095 // If the RecordDecl is actually the injected-class-name or a "templated"
2096 // declaration for a class template or class template partial
2097 // specialization, substitute into the injected-class-name of the
2098 // class template or partial specialization to find the new DeclContext.
2099 QualType T;
2100 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2101
2102 if (ClassTemplate) {
2103 T = ClassTemplate->getInjectedClassNameType(Context);
2104 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2105 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2106 T = Context.getTypeDeclType(Record);
2107 ClassTemplate = PartialSpec->getSpecializedTemplate();
2108 }
2109
2110 if (!T.isNull()) {
2111 // Substitute into the injected-class-name to get the type corresponding
2112 // to the instantiation we want. This substitution should never fail,
2113 // since we know we can instantiate the injected-class-name or we wouldn't
2114 // have gotten to the injected-class-name!
2115 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2116 // instantiation in the common case?
2117 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2118 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2119
2120 if (!T->isDependentType()) {
2121 assert(T->isRecordType() && "Instantiation must produce a record type");
2122 return T->getAs<RecordType>()->getDecl();
2123 }
2124
2125 // We are performing "partial" template instantiation to create the
2126 // member declarations for the members of a class template
2127 // specialization. Therefore, D is actually referring to something in
2128 // the current instantiation. Look through the current context,
2129 // which contains actual instantiations, to find the instantiation of
2130 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002131 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002132 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002133 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002134 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002135 if (isInstantiationOf(ClassTemplate,
2136 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002137 return Spec;
2138 }
2139
Mike Stump1eb44332009-09-09 15:08:12 +00002140 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002141 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002142 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002143 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002144
2145 // Fall through to deal with other dependent record types (e.g.,
2146 // anonymous unions in class templates).
2147 }
John McCall52a575a2009-08-29 08:11:13 +00002148
Douglas Gregore95b4092009-09-16 18:34:49 +00002149 if (!ParentDC->isDependentContext())
2150 return D;
2151
2152 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002153 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002154 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Douglas Gregor815215d2009-05-27 05:35:12 +00002156 if (ParentDC != D->getDeclContext()) {
2157 // We performed some kind of instantiation in the parent context,
2158 // so now we need to look into the instantiated parent context to
2159 // find the instantiation of the declaration D.
2160 NamedDecl *Result = 0;
2161 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002162 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002163 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2164 } else {
2165 // Since we don't have a name for the entity we're looking for,
2166 // our only option is to walk through all of the declarations to
2167 // find that name. This will occur in a few cases:
2168 //
2169 // - anonymous struct/union within a template
2170 // - unnamed class/struct/union/enum within a template
2171 //
2172 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002173 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002174 ParentDC->decls_begin(),
2175 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002176 }
Mike Stump1eb44332009-09-09 15:08:12 +00002177
John McCall9f54ad42009-12-10 09:41:52 +00002178 // UsingShadowDecls can instantiate to nothing because of using hiding.
2179 assert((Result || isa<UsingShadowDecl>(D))
2180 && "Unable to find instantiation of declaration!");
2181
Douglas Gregor815215d2009-05-27 05:35:12 +00002182 D = Result;
2183 }
2184
Douglas Gregor815215d2009-05-27 05:35:12 +00002185 return D;
2186}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002187
Mike Stump1eb44332009-09-09 15:08:12 +00002188/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002189/// instantiations we have seen until this point.
2190void Sema::PerformPendingImplicitInstantiations() {
2191 while (!PendingImplicitInstantiations.empty()) {
2192 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002193 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Douglas Gregor7caa6822009-07-24 20:34:43 +00002195 // Instantiate function definitions
2196 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002197 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002198 Function->getLocation(), *this,
2199 Context.getSourceManager(),
2200 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002202 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002203 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002204 continue;
2205 }
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Douglas Gregor7caa6822009-07-24 20:34:43 +00002207 // Instantiate static data member definitions.
2208 VarDecl *Var = cast<VarDecl>(Inst.first);
2209 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002210
Mike Stump1eb44332009-09-09 15:08:12 +00002211 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002212 Var->getLocation(), *this,
2213 Context.getSourceManager(),
2214 "instantiating static data member "
2215 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Douglas Gregor7caa6822009-07-24 20:34:43 +00002217 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002218 }
2219}