blob: 69982be84b908d12d87eb9e3a9bc50e3171fdb6f [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000020#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000022
23using namespace clang;
24
25namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000026 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000027 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028 Sema &SemaRef;
29 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000030 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Anders Carlssond8fe2d52009-11-07 06:07:58 +000032 void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
43 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000046 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000047 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitFieldDecl(FieldDecl *D);
49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000052 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000053 Decl *VisitFunctionDecl(FunctionDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000055 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000056 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000058 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000059 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000060 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000061 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000062 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000063 Decl *VisitClassTemplatePartialSpecializationDecl(
64 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000065 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000067 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000068 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000069 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000070 Decl *VisitUsingDecl(UsingDecl *D);
71 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000072 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
73 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor8dbc2692009-03-17 21:15:40 +000075 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000076 Decl *VisitDecl(Decl *D) {
77 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
78 Diagnostic::Error,
79 "cannot instantiate %0 yet");
80 SemaRef.Diag(D->getLocation(), DiagID)
81 << D->getDeclKindName();
82
Douglas Gregor8dbc2692009-03-17 21:15:40 +000083 return 0;
84 }
Douglas Gregor5545e162009-03-24 00:38:23 +000085
John McCallfd810b12009-08-14 02:03:10 +000086 const LangOptions &getLangOptions() {
87 return SemaRef.getLangOptions();
88 }
89
Douglas Gregor5545e162009-03-24 00:38:23 +000090 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000091 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000092 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000093 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000094 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000095
96 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000097 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000098
99 bool InstantiateClassTemplatePartialSpecialization(
100 ClassTemplateDecl *ClassTemplate,
101 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000102 };
103}
104
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000105// FIXME: Is this too simple?
106void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
107 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
108 TmplAttr = TmplAttr->getNext()) {
109
110 // FIXME: Is cloning correct for all attributes?
111 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
112
113 New->addAttr(NewAttr);
114 }
115}
116
Douglas Gregor4f722be2009-03-25 15:45:12 +0000117Decl *
118TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
119 assert(false && "Translation units cannot be instantiated");
120 return D;
121}
122
123Decl *
124TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
125 assert(false && "Namespaces cannot be instantiated");
126 return D;
127}
128
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000129Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
130 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000131 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000132 if (DI->getType()->isDependentType()) {
133 DI = SemaRef.SubstType(DI, TemplateArgs,
134 D->getLocation(), D->getDeclName());
135 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000136 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000137 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 }
139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000141 // Create the new typedef
142 TypedefDecl *Typedef
143 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000144 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 if (Invalid)
146 Typedef->setInvalidDecl();
147
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000148 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000150 return Typedef;
151}
152
Douglas Gregor6eef5192009-12-14 19:27:10 +0000153/// \brief Instantiate the arguments provided as part of initialization.
154///
155/// \returns true if an error occurred, false otherwise.
156static bool InstantiateInitializationArguments(Sema &SemaRef,
157 Expr **Args, unsigned NumArgs,
158 const MultiLevelTemplateArgumentList &TemplateArgs,
159 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
160 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
161 for (unsigned I = 0; I != NumArgs; ++I) {
162 // When we hit the first defaulted argument, break out of the loop:
163 // we don't pass those default arguments on.
164 if (Args[I]->isDefaultArgument())
165 break;
166
167 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
168 if (Arg.isInvalid())
169 return true;
170
171 Expr *ArgExpr = (Expr *)Arg.get();
172 InitArgs.push_back(Arg.release());
173
174 // FIXME: We're faking all of the comma locations. Do we need them?
175 FakeCommaLocs.push_back(
176 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
177 }
178
179 return false;
180}
181
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000182Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000183 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000184 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000185 TemplateArgs,
186 D->getTypeSpecStartLoc(),
187 D->getDeclName());
188 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000189 return 0;
190
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000191 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000192 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
193 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000194 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000195 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000196 Var->setThreadSpecified(D->isThreadSpecified());
197 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
198 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000199
200 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000201 // out-of-line, the instantiation will have the same lexical
202 // context (which will be a namespace scope) as the template.
203 if (D->isOutOfLine())
204 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Mike Stump390b4cc2009-05-16 07:39:55 +0000206 // FIXME: In theory, we could have a previous declaration for variables that
207 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000208 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000209 // FIXME: having to fake up a LookupResult is dumb.
210 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
211 Sema::LookupOrdinaryName);
212 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Douglas Gregor7caa6822009-07-24 20:34:43 +0000214 if (D->isOutOfLine()) {
215 D->getLexicalDeclContext()->addDecl(Var);
216 Owner->makeDeclVisibleInContext(Var);
217 } else {
218 Owner->addDecl(Var);
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000221 // Link instantiations of static data members back to the template from
222 // which they were instantiated.
223 if (Var->isStaticDataMember())
224 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000225 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000226
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000227 if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000228 if (Var->isStaticDataMember() && !D->isOutOfLine())
229 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
230 else
231 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
232
Douglas Gregor6eef5192009-12-14 19:27:10 +0000233 // Extract the initializer, skipping through any temporary-binding
234 // expressions and look at the subexpression as it was written.
235 Expr *DInit = D->getInit();
236 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
237 DInit = Binder->getSubExpr();
238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
239 DInit = ICE->getSubExprAsWritten();
240
241 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
242 // The initializer is a parenthesized list of expressions that is
243 // type-dependent. Instantiate each of the expressions; we'll be
244 // performing direct initialization with them.
245 llvm::SmallVector<SourceLocation, 4> CommaLocs;
246 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
247 if (!InstantiateInitializationArguments(SemaRef,
248 PLE->getExprs(),
249 PLE->getNumExprs(),
250 TemplateArgs,
251 CommaLocs, InitArgs)) {
252 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000253 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000254 PLE->getLParenLoc(),
255 move_arg(InitArgs),
256 CommaLocs.data(),
257 PLE->getRParenLoc());
258 }
259 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
260 // The initializer resolved to a constructor. Instantiate the constructor
261 // arguments.
262 llvm::SmallVector<SourceLocation, 4> CommaLocs;
263 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
264
265 if (!InstantiateInitializationArguments(SemaRef,
266 Construct->getArgs(),
267 Construct->getNumArgs(),
268 TemplateArgs,
269 CommaLocs, InitArgs)) {
270 if (D->hasCXXDirectInitializer()) {
271 SourceLocation FakeLParenLoc =
272 SemaRef.PP.getLocForEndOfToken(D->getLocation());
273 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
274 : CommaLocs.back();
275 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
276 FakeLParenLoc,
277 move_arg(InitArgs),
278 CommaLocs.data(),
279 FakeRParenLoc);
280 } else if (InitArgs.size() == 1) {
281 Expr *Init = (Expr*)(InitArgs.take()[0]);
282 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
283 SemaRef.Owned(Init),
284 false);
285 } else {
286 assert(InitArgs.size() == 0);
287 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
288 }
289 }
290 } else {
291 OwningExprResult Init
292 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
293
294 // FIXME: Not happy about invalidating decls just because of a bad
295 // initializer, unless it affects the type.
296 if (Init.isInvalid())
297 Var->setInvalidDecl();
298 else
299 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
300 D->hasCXXDirectInitializer());
301 }
302
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000303 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000304 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
305 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000306
307 return Var;
308}
309
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000310Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
311 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000312 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000313 if (DI->getType()->isDependentType()) {
314 DI = SemaRef.SubstType(DI, TemplateArgs,
315 D->getLocation(), D->getDeclName());
316 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000317 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000318 Invalid = true;
319 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000320 // C++ [temp.arg.type]p3:
321 // If a declaration acquires a function type through a type
322 // dependent on a template-parameter and this causes a
323 // declaration that does not use the syntactic form of a
324 // function declarator to have function type, the program is
325 // ill-formed.
326 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000327 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000328 Invalid = true;
329 }
330 }
331
332 Expr *BitWidth = D->getBitWidth();
333 if (Invalid)
334 BitWidth = 0;
335 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000336 // The bit-width expression is not potentially evaluated.
337 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000339 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000340 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000341 if (InstantiatedBitWidth.isInvalid()) {
342 Invalid = true;
343 BitWidth = 0;
344 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000345 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000346 }
347
John McCall07fb6be2009-10-22 23:33:21 +0000348 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
349 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000351 D->getLocation(),
352 D->isMutable(),
353 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000354 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000355 D->getAccess(),
356 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000357 if (!Field) {
358 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000359 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000362 InstantiateAttrs(D, Field);
363
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000364 if (Invalid)
365 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000367 if (!Field->getDeclName()) {
368 // Keep track of where this decl came from.
369 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000372 Field->setImplicit(D->isImplicit());
373 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000374
375 return Field;
376}
377
John McCall02cace72009-08-28 07:59:38 +0000378Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
379 FriendDecl::FriendUnion FU;
380
381 // Handle friend type expressions by simply substituting template
382 // parameters into the pattern type.
383 if (Type *Ty = D->getFriendType()) {
384 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
385 D->getLocation(), DeclarationName());
386 if (T.isNull()) return 0;
387
388 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
389 FU = T.getTypePtr();
390
391 // Handle everything else by appropriate substitution.
392 } else {
393 NamedDecl *ND = D->getFriendDecl();
394 assert(ND && "friend decl must be a decl or a type!");
395
Douglas Gregora735b202009-10-13 14:39:41 +0000396 // FIXME: We have a problem here, because the nested call to Visit(ND)
397 // will inject the thing that the friend references into the current
398 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000399 Decl *NewND = Visit(ND);
400 if (!NewND) return 0;
401
402 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
John McCall02cace72009-08-28 07:59:38 +0000405 FriendDecl *FD =
406 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
407 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000408 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000409 Owner->addDecl(FD);
410 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000411}
412
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000413Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
414 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Douglas Gregorac7610d2009-06-22 20:57:11 +0000416 // The expression in a static assertion is not potentially evaluated.
417 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000419 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000420 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000421 if (InstantiatedAssertExpr.isInvalid())
422 return 0;
423
Douglas Gregor43d9d922009-08-08 01:41:12 +0000424 OwningExprResult Message(SemaRef, D->getMessage());
425 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000426 Decl *StaticAssert
427 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000428 move(InstantiatedAssertExpr),
429 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 return StaticAssert;
431}
432
433Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000435 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000436 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000437 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000438 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000439 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000440 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441 Enum->startDefinition();
442
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000443 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000444
445 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000446 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
447 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000448 EC != ECEnd; ++EC) {
449 // The specified value for the enumerator.
450 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000451 if (Expr *UninstValue = EC->getInitExpr()) {
452 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000453 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000454 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
John McCallce3ff2b2009-08-25 22:02:44 +0000456 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000457 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000458
459 // Drop the initial value and continue.
460 bool isInvalid = false;
461 if (Value.isInvalid()) {
462 Value = SemaRef.Owned((Expr *)0);
463 isInvalid = true;
464 }
465
Mike Stump1eb44332009-09-09 15:08:12 +0000466 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000467 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
468 EC->getLocation(), EC->getIdentifier(),
469 move(Value));
470
471 if (isInvalid) {
472 if (EnumConst)
473 EnumConst->setInvalidDecl();
474 Enum->setInvalidDecl();
475 }
476
477 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000478 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000479 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000480 LastEnumConst = EnumConst;
481 }
482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000484 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000485 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000486 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
487 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000488 &Enumerators[0], Enumerators.size(),
489 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000490
491 return Enum;
492}
493
Douglas Gregor6477b692009-03-25 15:04:13 +0000494Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
495 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
496 return 0;
497}
498
Douglas Gregored9c0f92009-10-29 00:04:11 +0000499namespace {
500 class SortDeclByLocation {
501 SourceManager &SourceMgr;
502
503 public:
504 explicit SortDeclByLocation(SourceManager &SourceMgr)
505 : SourceMgr(SourceMgr) { }
506
507 bool operator()(const Decl *X, const Decl *Y) const {
508 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
509 Y->getLocation());
510 }
511 };
512}
513
John McCalle29ba202009-08-20 01:44:21 +0000514Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000515 // Create a local instantiation scope for this class template, which
516 // will contain the instantiations of the template parameters.
517 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000518 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000519 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000520 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000521 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000522
523 CXXRecordDecl *Pattern = D->getTemplatedDecl();
524 CXXRecordDecl *RecordInst
525 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
526 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000527 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
528 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000529
530 ClassTemplateDecl *Inst
531 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
532 D->getIdentifier(), InstParams, RecordInst, 0);
533 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000534 if (D->getFriendObjectKind())
535 Inst->setObjectOfFriendDecl(true);
536 else
537 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000538 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000539
540 // Trigger creation of the type for the instantiation.
541 SemaRef.Context.getTypeDeclType(RecordInst);
542
Douglas Gregor259571e2009-10-30 22:42:42 +0000543 // Finish handling of friends.
544 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000545 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000546 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000547
John McCalle29ba202009-08-20 01:44:21 +0000548 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000549
550 // First, we sort the partial specializations by location, so
551 // that we instantiate them in the order they were declared.
552 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
553 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
554 P = D->getPartialSpecializations().begin(),
555 PEnd = D->getPartialSpecializations().end();
556 P != PEnd; ++P)
557 PartialSpecs.push_back(&*P);
558 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
559 SortDeclByLocation(SemaRef.SourceMgr));
560
561 // Instantiate all of the partial specializations of this member class
562 // template.
563 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
564 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
565
John McCalle29ba202009-08-20 01:44:21 +0000566 return Inst;
567}
568
Douglas Gregord60e1052009-08-27 16:57:43 +0000569Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000570TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
571 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000572 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
573
574 // Lookup the already-instantiated declaration in the instantiation
575 // of the class template and return that.
576 DeclContext::lookup_result Found
577 = Owner->lookup(ClassTemplate->getDeclName());
578 if (Found.first == Found.second)
579 return 0;
580
581 ClassTemplateDecl *InstClassTemplate
582 = dyn_cast<ClassTemplateDecl>(*Found.first);
583 if (!InstClassTemplate)
584 return 0;
585
586 Decl *DCanon = D->getCanonicalDecl();
587 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
588 P = InstClassTemplate->getPartialSpecializations().begin(),
589 PEnd = InstClassTemplate->getPartialSpecializations().end();
590 P != PEnd; ++P) {
591 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
592 return &*P;
593 }
594
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000595 return 0;
596}
597
598Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000599TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000600 // Create a local instantiation scope for this function template, which
601 // will contain the instantiations of the template parameters and then get
602 // merged with the local instantiation scope for the function template
603 // itself.
604 Sema::LocalInstantiationScope Scope(SemaRef);
605
Douglas Gregord60e1052009-08-27 16:57:43 +0000606 TemplateParameterList *TempParams = D->getTemplateParameters();
607 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000608 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000609 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000610
Douglas Gregora735b202009-10-13 14:39:41 +0000611 FunctionDecl *Instantiated = 0;
612 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
613 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
614 InstParams));
615 else
616 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
617 D->getTemplatedDecl(),
618 InstParams));
619
620 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000621 return 0;
622
Mike Stump1eb44332009-09-09 15:08:12 +0000623 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000624 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000625 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000626 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000627 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000628 assert(InstTemplate &&
629 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000630
631 // Link the instantiation back to the pattern *unless* this is a
632 // non-definition friend declaration.
633 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
634 !(InstTemplate->getFriendObjectKind() &&
635 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000636 InstTemplate->setInstantiatedFromMemberTemplate(D);
637
638 // Add non-friends into the owner.
639 if (!InstTemplate->getFriendObjectKind())
640 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000641 return InstTemplate;
642}
643
Douglas Gregord475b8d2009-03-25 21:17:03 +0000644Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
645 CXXRecordDecl *PrevDecl = 0;
646 if (D->isInjectedClassName())
647 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000648 else if (D->getPreviousDeclaration()) {
649 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
650 TemplateArgs);
651 if (!Prev) return 0;
652 PrevDecl = cast<CXXRecordDecl>(Prev);
653 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000654
655 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000656 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000657 D->getLocation(), D->getIdentifier(),
658 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000659 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000660 // FIXME: Check against AS_none is an ugly hack to work around the issue that
661 // the tag decls introduced by friend class declarations don't have an access
662 // specifier. Remove once this area of the code gets sorted out.
663 if (D->getAccess() != AS_none)
664 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000665 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000666 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000667
John McCall02cace72009-08-28 07:59:38 +0000668 // If the original function was part of a friend declaration,
669 // inherit its namespace state.
670 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
671 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
672
Anders Carlssond8b285f2009-09-01 04:26:58 +0000673 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
674
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000675 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000676 return Record;
677}
678
John McCall02cace72009-08-28 07:59:38 +0000679/// Normal class members are of more specific types and therefore
680/// don't make it here. This function serves two purposes:
681/// 1) instantiating function templates
682/// 2) substituting friend declarations
683/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000684 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
685 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000686 // Check whether there is already a function template specialization for
687 // this declaration.
688 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
689 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000690 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000691 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000692 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000693 TemplateArgs.getInnermost().getFlatArgumentList(),
694 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000695 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
697 FunctionTemplateSpecializationInfo *Info
698 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000699 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Douglas Gregor127102b2009-06-29 20:59:39 +0000701 // If we already have a function template specialization, return it.
702 if (Info)
703 return Info->Function;
704 }
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Douglas Gregor550d9b22009-10-31 17:21:17 +0000706 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Douglas Gregore53060f2009-06-25 22:08:12 +0000708 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000709 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000710 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000711 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000712
Douglas Gregore53060f2009-06-25 22:08:12 +0000713 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000714 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
715 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000716 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000717 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000718 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000719 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000720 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000721 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Douglas Gregore53060f2009-06-25 22:08:12 +0000723 // Attach the parameters
724 for (unsigned P = 0; P < Params.size(); ++P)
725 Params[P]->setOwningFunction(Function);
726 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000727
Douglas Gregora735b202009-10-13 14:39:41 +0000728 if (TemplateParams) {
729 // Our resulting instantiation is actually a function template, since we
730 // are substituting only the outer template parameters. For example, given
731 //
732 // template<typename T>
733 // struct X {
734 // template<typename U> friend void f(T, U);
735 // };
736 //
737 // X<int> x;
738 //
739 // We are instantiating the friend function template "f" within X<int>,
740 // which means substituting int for T, but leaving "f" as a friend function
741 // template.
742 // Build the function template itself.
743 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
744 Function->getLocation(),
745 Function->getDeclName(),
746 TemplateParams, Function);
747 Function->setDescribedFunctionTemplate(FunctionTemplate);
748 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000749 } else if (FunctionTemplate) {
750 // Record this function template specialization.
751 Function->setFunctionTemplateSpecialization(SemaRef.Context,
752 FunctionTemplate,
753 &TemplateArgs.getInnermost(),
754 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000755 }
Douglas Gregora735b202009-10-13 14:39:41 +0000756
Douglas Gregore53060f2009-06-25 22:08:12 +0000757 if (InitFunctionInstantiation(Function, D))
758 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Douglas Gregore53060f2009-06-25 22:08:12 +0000760 bool Redeclaration = false;
761 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000762
John McCall68263142009-11-18 22:49:29 +0000763 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
764 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
765
Douglas Gregora735b202009-10-13 14:39:41 +0000766 if (TemplateParams || !FunctionTemplate) {
767 // Look only into the namespace where the friend would be declared to
768 // find a previous declaration. This is the innermost enclosing namespace,
769 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000770 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000771
Douglas Gregora735b202009-10-13 14:39:41 +0000772 // In C++, the previous declaration we find might be a tag type
773 // (class or enum). In this case, the new declaration will hide the
774 // tag type. Note that this does does not apply if we're declaring a
775 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000776 if (Previous.isSingleTagDecl())
777 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000778 }
779
John McCall9f54ad42009-12-10 09:41:52 +0000780 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
781 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000782 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000783
Douglas Gregora735b202009-10-13 14:39:41 +0000784 // If the original function was part of a friend declaration,
785 // inherit its namespace state and add it to the owner.
786 NamedDecl *FromFriendD
787 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
788 if (FromFriendD->getFriendObjectKind()) {
789 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000790 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000791 if (TemplateParams) {
792 ToFriendD = cast<NamedDecl>(FunctionTemplate);
793 PrevDecl = FunctionTemplate->getPreviousDeclaration();
794 } else {
795 ToFriendD = Function;
796 PrevDecl = Function->getPreviousDeclaration();
797 }
798 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
799 if (!Owner->isDependentContext() && !PrevDecl)
800 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
801
802 if (!TemplateParams)
803 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
804 }
805
Douglas Gregore53060f2009-06-25 22:08:12 +0000806 return Function;
807}
808
Douglas Gregord60e1052009-08-27 16:57:43 +0000809Decl *
810TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
811 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000812 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
813 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000814 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000815 // We are creating a function template specialization from a function
816 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000817 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000818 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000819 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000820 TemplateArgs.getInnermost().getFlatArgumentList(),
821 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000822 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000823
824 FunctionTemplateSpecializationInfo *Info
825 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000826 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Douglas Gregor6b906862009-08-21 00:16:32 +0000828 // If we already have a function template specialization, return it.
829 if (Info)
830 return Info->Function;
831 }
832
Douglas Gregor550d9b22009-10-31 17:21:17 +0000833 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000834
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000835 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000836 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000837 if (T.isNull())
838 return 0;
839
840 // Build the instantiated method declaration.
841 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000842 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Douglas Gregordec06662009-08-21 18:42:58 +0000844 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000845 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000846 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
847 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
848 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000849 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
850 Constructor->getLocation(),
851 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000852 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000853 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000854 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000855 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
856 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
857 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
858 SemaRef.Context.getCanonicalType(ClassTy));
859 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
860 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000861 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000862 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000863 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000864 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000865 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000866 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
867 ConvTy);
868 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
869 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000870 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000871 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000872 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000873 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000874 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000875 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000876 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000877 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000878
Douglas Gregord60e1052009-08-27 16:57:43 +0000879 if (TemplateParams) {
880 // Our resulting instantiation is actually a function template, since we
881 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000882 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000883 // template<typename T>
884 // struct X {
885 // template<typename U> void f(T, U);
886 // };
887 //
888 // X<int> x;
889 //
890 // We are instantiating the member template "f" within X<int>, which means
891 // substituting int for T, but leaving "f" as a member function template.
892 // Build the function template itself.
893 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
894 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000895 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000896 TemplateParams, Method);
897 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000898 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000899 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000900 } else if (FunctionTemplate) {
901 // Record this function template specialization.
902 Method->setFunctionTemplateSpecialization(SemaRef.Context,
903 FunctionTemplate,
904 &TemplateArgs.getInnermost(),
905 InsertPos);
906 } else {
907 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000908 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000909 }
910
Mike Stump1eb44332009-09-09 15:08:12 +0000911 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000912 // out-of-line, the instantiation will have the same lexical
913 // context (which will be a namespace scope) as the template.
914 if (D->isOutOfLine())
915 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Douglas Gregor5545e162009-03-24 00:38:23 +0000917 // Attach the parameters
918 for (unsigned P = 0; P < Params.size(); ++P)
919 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000920 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000921
922 if (InitMethodInstantiation(Method, D))
923 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000924
John McCall68263142009-11-18 22:49:29 +0000925 LookupResult Previous(SemaRef, Name, SourceLocation(),
926 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregord60e1052009-08-27 16:57:43 +0000928 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000929 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregordec06662009-08-21 18:42:58 +0000931 // In C++, the previous declaration we find might be a tag type
932 // (class or enum). In this case, the new declaration will hide the
933 // tag type. Note that this does does not apply if we're declaring a
934 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000935 if (Previous.isSingleTagDecl())
936 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +0000937 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000938
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000939 bool Redeclaration = false;
940 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +0000941 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000942 /*FIXME:*/OverloadableAttrRequired);
943
Douglas Gregor4ba31362009-12-01 17:24:26 +0000944 if (D->isPure())
945 SemaRef.CheckPureMethod(Method, SourceRange());
946
John McCall68263142009-11-18 22:49:29 +0000947 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +0000948 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000949 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000951 return Method;
952}
953
Douglas Gregor615c5d42009-03-24 16:43:20 +0000954Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000955 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000956}
957
Douglas Gregor03b2b072009-03-24 00:15:49 +0000958Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000959 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000960}
961
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000962Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000963 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000964}
965
Douglas Gregor6477b692009-03-25 15:04:13 +0000966ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000967 QualType T;
John McCalla93c9342009-12-07 02:54:59 +0000968 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +0000969 if (DI) {
970 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
971 D->getDeclName());
972 if (DI) T = DI->getType();
973 } else {
974 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
975 D->getDeclName());
976 DI = 0;
977 }
978
979 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000980 return 0;
981
John McCall58e46772009-10-23 21:48:59 +0000982 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000983
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000984 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000985 ParmVarDecl *Param
986 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
987 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000988
Anders Carlsson9351c172009-08-25 03:18:48 +0000989 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000990 if (D->hasUninstantiatedDefaultArg())
991 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000992 else if (Expr *Arg = D->getDefaultArg())
993 Param->setUninstantiatedDefaultArg(Arg);
994
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000995 // Note: we don't try to instantiate function parameters until after
996 // we've instantiated the function's type. Therefore, we don't have
997 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000998 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000999 return Param;
1000}
1001
John McCalle29ba202009-08-20 01:44:21 +00001002Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1003 TemplateTypeParmDecl *D) {
1004 // TODO: don't always clone when decls are refcounted.
1005 const Type* T = D->getTypeForDecl();
1006 assert(T->isTemplateTypeParmType());
1007 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
John McCalle29ba202009-08-20 01:44:21 +00001009 TemplateTypeParmDecl *Inst =
1010 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001011 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001012 TTPT->getName(),
1013 D->wasDeclaredWithTypename(),
1014 D->isParameterPack());
1015
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001016 if (D->hasDefaultArgument())
1017 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001018
Douglas Gregor550d9b22009-10-31 17:21:17 +00001019 // Introduce this template parameter's instantiation into the instantiation
1020 // scope.
1021 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1022
John McCalle29ba202009-08-20 01:44:21 +00001023 return Inst;
1024}
1025
Douglas Gregor33642df2009-10-23 23:25:44 +00001026Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1027 NonTypeTemplateParmDecl *D) {
1028 // Substitute into the type of the non-type template parameter.
1029 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001030 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001031 if (DI) {
1032 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1033 D->getDeclName());
1034 if (DI) T = DI->getType();
1035 } else {
1036 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1037 D->getDeclName());
1038 DI = 0;
1039 }
1040 if (T.isNull())
1041 return 0;
1042
1043 // Check that this type is acceptable for a non-type template parameter.
1044 bool Invalid = false;
1045 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1046 if (T.isNull()) {
1047 T = SemaRef.Context.IntTy;
1048 Invalid = true;
1049 }
1050
1051 NonTypeTemplateParmDecl *Param
1052 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1053 D->getDepth() - 1, D->getPosition(),
1054 D->getIdentifier(), T, DI);
1055 if (Invalid)
1056 Param->setInvalidDecl();
1057
1058 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001059
1060 // Introduce this template parameter's instantiation into the instantiation
1061 // scope.
1062 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001063 return Param;
1064}
1065
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001066Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001067TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1068 TemplateTemplateParmDecl *D) {
1069 // Instantiate the template parameter list of the template template parameter.
1070 TemplateParameterList *TempParams = D->getTemplateParameters();
1071 TemplateParameterList *InstParams;
1072 {
1073 // Perform the actual substitution of template parameters within a new,
1074 // local instantiation scope.
1075 Sema::LocalInstantiationScope Scope(SemaRef);
1076 InstParams = SubstTemplateParams(TempParams);
1077 if (!InstParams)
1078 return NULL;
1079 }
1080
1081 // Build the template template parameter.
1082 TemplateTemplateParmDecl *Param
1083 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1084 D->getDepth() - 1, D->getPosition(),
1085 D->getIdentifier(), InstParams);
1086 Param->setDefaultArgument(D->getDefaultArgument());
1087
1088 // Introduce this template parameter's instantiation into the instantiation
1089 // scope.
1090 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1091
1092 return Param;
1093}
1094
Douglas Gregor48c32a72009-11-17 06:07:40 +00001095Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1096 // Using directives are never dependent, so they require no explicit
1097
1098 UsingDirectiveDecl *Inst
1099 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1100 D->getNamespaceKeyLocation(),
1101 D->getQualifierRange(), D->getQualifier(),
1102 D->getIdentLocation(),
1103 D->getNominatedNamespace(),
1104 D->getCommonAncestor());
1105 Owner->addDecl(Inst);
1106 return Inst;
1107}
1108
John McCalled976492009-12-04 22:46:56 +00001109Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1110 // The nested name specifier is non-dependent, so no transformation
1111 // is required.
1112
John McCall9f54ad42009-12-10 09:41:52 +00001113 // We only need to do redeclaration lookups if we're in a class
1114 // scope (in fact, it's not really even possible in non-class
1115 // scopes).
1116 bool CheckRedeclaration = Owner->isRecord();
1117
1118 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1119 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1120
John McCalled976492009-12-04 22:46:56 +00001121 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1122 D->getLocation(),
1123 D->getNestedNameRange(),
1124 D->getUsingLocation(),
1125 D->getTargetNestedNameDecl(),
1126 D->getDeclName(),
1127 D->isTypeName());
1128
1129 CXXScopeSpec SS;
1130 SS.setScopeRep(D->getTargetNestedNameDecl());
1131 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001132
1133 if (CheckRedeclaration) {
1134 Prev.setHideTags(false);
1135 SemaRef.LookupQualifiedName(Prev, Owner);
1136
1137 // Check for invalid redeclarations.
1138 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1139 D->isTypeName(), SS,
1140 D->getLocation(), Prev))
1141 NewUD->setInvalidDecl();
1142
1143 }
1144
1145 if (!NewUD->isInvalidDecl() &&
1146 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001147 D->getLocation()))
1148 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001149
John McCalled976492009-12-04 22:46:56 +00001150 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1151 NewUD->setAccess(D->getAccess());
1152 Owner->addDecl(NewUD);
1153
John McCall9f54ad42009-12-10 09:41:52 +00001154 // Don't process the shadow decls for an invalid decl.
1155 if (NewUD->isInvalidDecl())
1156 return NewUD;
1157
1158 // Process the shadow decls.
1159 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1160 I != E; ++I) {
1161 UsingShadowDecl *Shadow = *I;
1162 NamedDecl *InstTarget =
1163 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1164 TemplateArgs));
1165
1166 if (CheckRedeclaration &&
1167 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1168 continue;
1169
1170 UsingShadowDecl *InstShadow
1171 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1172 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1173 }
John McCalled976492009-12-04 22:46:56 +00001174
1175 return NewUD;
1176}
1177
1178Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001179 // Ignore these; we handle them in bulk when processing the UsingDecl.
1180 return 0;
John McCalled976492009-12-04 22:46:56 +00001181}
1182
John McCall7ba107a2009-11-18 02:36:19 +00001183Decl * TemplateDeclInstantiator
1184 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001185 NestedNameSpecifier *NNS =
1186 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1187 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001188 TemplateArgs);
1189 if (!NNS)
1190 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001192 CXXScopeSpec SS;
1193 SS.setRange(D->getTargetNestedNameRange());
1194 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001195
1196 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001197 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001198 D->getUsingLoc(), SS, D->getLocation(),
1199 D->getDeclName(), 0,
1200 /*instantiation*/ true,
1201 /*typename*/ true, D->getTypenameLoc());
1202 if (UD)
John McCalled976492009-12-04 22:46:56 +00001203 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1204
John McCall7ba107a2009-11-18 02:36:19 +00001205 return UD;
1206}
1207
1208Decl * TemplateDeclInstantiator
1209 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1210 NestedNameSpecifier *NNS =
1211 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1212 D->getTargetNestedNameRange(),
1213 TemplateArgs);
1214 if (!NNS)
1215 return 0;
1216
1217 CXXScopeSpec SS;
1218 SS.setRange(D->getTargetNestedNameRange());
1219 SS.setScopeRep(NNS);
1220
1221 NamedDecl *UD =
1222 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1223 D->getUsingLoc(), SS, D->getLocation(),
1224 D->getDeclName(), 0,
1225 /*instantiation*/ true,
1226 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001227 if (UD)
John McCalled976492009-12-04 22:46:56 +00001228 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1229
Anders Carlsson0d8df782009-08-29 19:37:28 +00001230 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001231}
1232
John McCallce3ff2b2009-08-25 22:02:44 +00001233Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001234 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001235 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001236 return Instantiator.Visit(D);
1237}
1238
John McCalle29ba202009-08-20 01:44:21 +00001239/// \brief Instantiates a nested template parameter list in the current
1240/// instantiation context.
1241///
1242/// \param L The parameter list to instantiate
1243///
1244/// \returns NULL if there was an error
1245TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001246TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001247 // Get errors for all the parameters before bailing out.
1248 bool Invalid = false;
1249
1250 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001251 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001252 ParamVector Params;
1253 Params.reserve(N);
1254 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1255 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001256 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001257 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001258 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001259 }
1260
1261 // Clean up if we had an error.
1262 if (Invalid) {
1263 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1264 PI != PE; ++PI)
1265 if (*PI)
1266 (*PI)->Destroy(SemaRef.Context);
1267 return NULL;
1268 }
1269
1270 TemplateParameterList *InstL
1271 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1272 L->getLAngleLoc(), &Params.front(), N,
1273 L->getRAngleLoc());
1274 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001275}
John McCalle29ba202009-08-20 01:44:21 +00001276
Douglas Gregored9c0f92009-10-29 00:04:11 +00001277/// \brief Instantiate the declaration of a class template partial
1278/// specialization.
1279///
1280/// \param ClassTemplate the (instantiated) class template that is partially
1281// specialized by the instantiation of \p PartialSpec.
1282///
1283/// \param PartialSpec the (uninstantiated) class template partial
1284/// specialization that we are instantiating.
1285///
1286/// \returns true if there was an error, false otherwise.
1287bool
1288TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1289 ClassTemplateDecl *ClassTemplate,
1290 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001291 // Create a local instantiation scope for this class template partial
1292 // specialization, which will contain the instantiations of the template
1293 // parameters.
1294 Sema::LocalInstantiationScope Scope(SemaRef);
1295
Douglas Gregored9c0f92009-10-29 00:04:11 +00001296 // Substitute into the template parameters of the class template partial
1297 // specialization.
1298 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1299 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1300 if (!InstParams)
1301 return true;
1302
1303 // Substitute into the template arguments of the class template partial
1304 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001305 const TemplateArgumentLoc *PartialSpecTemplateArgs
1306 = PartialSpec->getTemplateArgsAsWritten();
1307 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1308
John McCalld5532b62009-11-23 01:53:49 +00001309 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001310 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001311 TemplateArgumentLoc Loc;
1312 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001313 return true;
John McCalld5532b62009-11-23 01:53:49 +00001314 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001315 }
1316
1317
1318 // Check that the template argument list is well-formed for this
1319 // class template.
1320 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1321 InstTemplateArgs.size());
1322 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1323 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001324 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001325 false,
1326 Converted))
1327 return true;
1328
1329 // Figure out where to insert this class template partial specialization
1330 // in the member template's set of class template partial specializations.
1331 llvm::FoldingSetNodeID ID;
1332 ClassTemplatePartialSpecializationDecl::Profile(ID,
1333 Converted.getFlatArguments(),
1334 Converted.flatSize(),
1335 SemaRef.Context);
1336 void *InsertPos = 0;
1337 ClassTemplateSpecializationDecl *PrevDecl
1338 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1339 InsertPos);
1340
1341 // Build the canonical type that describes the converted template
1342 // arguments of the class template partial specialization.
1343 QualType CanonType
1344 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1345 Converted.getFlatArguments(),
1346 Converted.flatSize());
1347
1348 // Build the fully-sugared type for this class template
1349 // specialization as the user wrote in the specialization
1350 // itself. This means that we'll pretty-print the type retrieved
1351 // from the specialization's declaration the way that the user
1352 // actually wrote the specialization, rather than formatting the
1353 // name based on the "canonical" representation used to store the
1354 // template arguments in the specialization.
1355 QualType WrittenTy
1356 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001357 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001358 CanonType);
1359
1360 if (PrevDecl) {
1361 // We've already seen a partial specialization with the same template
1362 // parameters and template arguments. This can happen, for example, when
1363 // substituting the outer template arguments ends up causing two
1364 // class template partial specializations of a member class template
1365 // to have identical forms, e.g.,
1366 //
1367 // template<typename T, typename U>
1368 // struct Outer {
1369 // template<typename X, typename Y> struct Inner;
1370 // template<typename Y> struct Inner<T, Y>;
1371 // template<typename Y> struct Inner<U, Y>;
1372 // };
1373 //
1374 // Outer<int, int> outer; // error: the partial specializations of Inner
1375 // // have the same signature.
1376 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1377 << WrittenTy;
1378 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1379 << SemaRef.Context.getTypeDeclType(PrevDecl);
1380 return true;
1381 }
1382
1383
1384 // Create the class template partial specialization declaration.
1385 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1386 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1387 PartialSpec->getLocation(),
1388 InstParams,
1389 ClassTemplate,
1390 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001391 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001392 0);
1393 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1394 InstPartialSpec->setTypeAsWritten(WrittenTy);
1395
1396 // Add this partial specialization to the set of class template partial
1397 // specializations.
1398 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1399 InsertPos);
1400 return false;
1401}
1402
John McCallce3ff2b2009-08-25 22:02:44 +00001403/// \brief Does substitution on the type of the given function, including
1404/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001405///
John McCallce3ff2b2009-08-25 22:02:44 +00001406/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001407///
1408/// \param Params the instantiated parameter declarations
1409
John McCallce3ff2b2009-08-25 22:02:44 +00001410/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001411/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001412QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001413TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001414 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1415 bool InvalidDecl = false;
1416
John McCallce3ff2b2009-08-25 22:02:44 +00001417 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001418 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001419 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001420 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001421 PEnd = D->param_end();
1422 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001423 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001424 if (PInst->getType()->isVoidType()) {
1425 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1426 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001427 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001428 PInst->getType(),
1429 diag::err_abstract_type_in_decl,
1430 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001431 PInst->setInvalidDecl();
1432
1433 Params.push_back(PInst);
1434 ParamTys.push_back(PInst->getType());
1435
1436 if (PInst->isInvalidDecl())
1437 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001438 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001439 InvalidDecl = true;
1440 }
1441
1442 // FIXME: Deallocate dead declarations.
1443 if (InvalidDecl)
1444 return QualType();
1445
John McCall183700f2009-09-21 23:43:11 +00001446 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001447 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001448 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001449 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1450 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001451 if (ResultType.isNull())
1452 return QualType();
1453
Jay Foadbeaaccd2009-05-21 09:52:38 +00001454 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001455 Proto->isVariadic(), Proto->getTypeQuals(),
1456 D->getLocation(), D->getDeclName());
1457}
1458
Mike Stump1eb44332009-09-09 15:08:12 +00001459/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001460/// declaration (New) from the corresponding fields of its template (Tmpl).
1461///
1462/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001463bool
1464TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001465 FunctionDecl *Tmpl) {
1466 if (Tmpl->isDeleted())
1467 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregorcca9e962009-07-01 22:01:06 +00001469 // If we are performing substituting explicitly-specified template arguments
1470 // or deduced template arguments into a function template and we reach this
1471 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001472 // to keeping the new function template specialization. We therefore
1473 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001474 // into a template instantiation for this specific function template
1475 // specialization, which is not a SFINAE context, so that we diagnose any
1476 // further errors in the declaration itself.
1477 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1478 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1479 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1480 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001481 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001482 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001483 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001484 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001485 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001486 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1487 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001488 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001489 }
1490 }
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001492 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1493 assert(Proto && "Function template without prototype?");
1494
1495 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1496 Proto->getNoReturnAttr()) {
1497 // The function has an exception specification or a "noreturn"
1498 // attribute. Substitute into each of the exception types.
1499 llvm::SmallVector<QualType, 4> Exceptions;
1500 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1501 // FIXME: Poor location information!
1502 QualType T
1503 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1504 New->getLocation(), New->getDeclName());
1505 if (T.isNull() ||
1506 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1507 continue;
1508
1509 Exceptions.push_back(T);
1510 }
1511
1512 // Rebuild the function type
1513
1514 const FunctionProtoType *NewProto
1515 = New->getType()->getAs<FunctionProtoType>();
1516 assert(NewProto && "Template instantiation without function prototype?");
1517 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1518 NewProto->arg_type_begin(),
1519 NewProto->getNumArgs(),
1520 NewProto->isVariadic(),
1521 NewProto->getTypeQuals(),
1522 Proto->hasExceptionSpec(),
1523 Proto->hasAnyExceptionSpec(),
1524 Exceptions.size(),
1525 Exceptions.data(),
1526 Proto->getNoReturnAttr()));
1527 }
1528
Douglas Gregore53060f2009-06-25 22:08:12 +00001529 return false;
1530}
1531
Douglas Gregor5545e162009-03-24 00:38:23 +00001532/// \brief Initializes common fields of an instantiated method
1533/// declaration (New) from the corresponding fields of its template
1534/// (Tmpl).
1535///
1536/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001537bool
1538TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001539 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001540 if (InitFunctionInstantiation(New, Tmpl))
1541 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Douglas Gregor5545e162009-03-24 00:38:23 +00001543 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1544 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001545 if (Tmpl->isVirtualAsWritten())
1546 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001547
1548 // FIXME: attributes
1549 // FIXME: New needs a pointer to Tmpl
1550 return false;
1551}
Douglas Gregora58861f2009-05-13 20:28:22 +00001552
1553/// \brief Instantiate the definition of the given function from its
1554/// template.
1555///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001556/// \param PointOfInstantiation the point at which the instantiation was
1557/// required. Note that this is not precisely a "point of instantiation"
1558/// for the function, but it's close.
1559///
Douglas Gregora58861f2009-05-13 20:28:22 +00001560/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001561/// function template specialization or member function of a class template
1562/// specialization.
1563///
1564/// \param Recursive if true, recursively instantiates any functions that
1565/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001566///
1567/// \param DefinitionRequired if true, then we are performing an explicit
1568/// instantiation where the body of the function is required. Complain if
1569/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001570void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001571 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001572 bool Recursive,
1573 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001574 if (Function->isInvalidDecl())
1575 return;
1576
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001577 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001579 // Never instantiate an explicit specialization.
1580 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1581 return;
1582
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001583 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001584 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001585 Stmt *Pattern = 0;
1586 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001587 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001588
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001589 if (!Pattern) {
1590 if (DefinitionRequired) {
1591 if (Function->getPrimaryTemplate())
1592 Diag(PointOfInstantiation,
1593 diag::err_explicit_instantiation_undefined_func_template)
1594 << Function->getPrimaryTemplate();
1595 else
1596 Diag(PointOfInstantiation,
1597 diag::err_explicit_instantiation_undefined_member)
1598 << 1 << Function->getDeclName() << Function->getDeclContext();
1599
1600 if (PatternDecl)
1601 Diag(PatternDecl->getLocation(),
1602 diag::note_explicit_instantiation_here);
1603 }
1604
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001605 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001606 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001607
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001608 // C++0x [temp.explicit]p9:
1609 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001610 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001611 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001612 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001613 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001614 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001615 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001617 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1618 if (Inst)
1619 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001620
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001621 // If we're performing recursive template instantiation, create our own
1622 // queue of pending implicit instantiations that we will instantiate later,
1623 // while we're still within our own instantiation context.
1624 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1625 if (Recursive)
1626 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001628 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1629
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001630 // Introduce a new scope where local variable instantiations will be
1631 // recorded.
1632 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001634 // Introduce the instantiated function parameters into the local
1635 // instantiation scope.
1636 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1637 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1638 Function->getParamDecl(I));
1639
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001640 // Enter the scope of this instantiation. We don't use
1641 // PushDeclContext because we don't have a scope.
1642 DeclContext *PreviousContext = CurContext;
1643 CurContext = Function;
1644
Mike Stump1eb44332009-09-09 15:08:12 +00001645 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001646 getTemplateInstantiationArgs(Function);
1647
1648 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001649 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001650 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1651 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1652 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001653 }
1654
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001655 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001656 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001657
Douglas Gregor52604ab2009-09-11 21:19:12 +00001658 if (Body.isInvalid())
1659 Function->setInvalidDecl();
1660
Mike Stump1eb44332009-09-09 15:08:12 +00001661 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001662 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001663
1664 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001665
1666 DeclGroupRef DG(Function);
1667 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001669 if (Recursive) {
1670 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001671 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001672 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001674 // Restore the set of pending implicit instantiations.
1675 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1676 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001677}
1678
1679/// \brief Instantiate the definition of the given variable from its
1680/// template.
1681///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001682/// \param PointOfInstantiation the point at which the instantiation was
1683/// required. Note that this is not precisely a "point of instantiation"
1684/// for the function, but it's close.
1685///
1686/// \param Var the already-instantiated declaration of a static member
1687/// variable of a class template specialization.
1688///
1689/// \param Recursive if true, recursively instantiates any functions that
1690/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001691///
1692/// \param DefinitionRequired if true, then we are performing an explicit
1693/// instantiation where an out-of-line definition of the member variable
1694/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001695void Sema::InstantiateStaticDataMemberDefinition(
1696 SourceLocation PointOfInstantiation,
1697 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001698 bool Recursive,
1699 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001700 if (Var->isInvalidDecl())
1701 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor7caa6822009-07-24 20:34:43 +00001703 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001704 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001705 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001706 assert(Def->isStaticDataMember() && "Not a static data member?");
1707 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor0d035142009-10-27 18:42:08 +00001709 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001710 // We did not find an out-of-line definition of this static data member,
1711 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001712 // instantiate this definition (or provide a specialization for it) in
1713 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001714 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001715 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001716 Diag(PointOfInstantiation,
1717 diag::err_explicit_instantiation_undefined_member)
1718 << 2 << Var->getDeclName() << Var->getDeclContext();
1719 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1720 }
1721
Douglas Gregor7caa6822009-07-24 20:34:43 +00001722 return;
1723 }
1724
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001725 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001726 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001727 return;
1728
1729 // C++0x [temp.explicit]p9:
1730 // Except for inline functions, other explicit instantiation declarations
1731 // have the effect of suppressing the implicit instantiation of the entity
1732 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001733 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001734 == TSK_ExplicitInstantiationDeclaration)
1735 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Douglas Gregor7caa6822009-07-24 20:34:43 +00001737 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1738 if (Inst)
1739 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Douglas Gregor7caa6822009-07-24 20:34:43 +00001741 // If we're performing recursive template instantiation, create our own
1742 // queue of pending implicit instantiations that we will instantiate later,
1743 // while we're still within our own instantiation context.
1744 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1745 if (Recursive)
1746 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Douglas Gregor7caa6822009-07-24 20:34:43 +00001748 // Enter the scope of this instantiation. We don't use
1749 // PushDeclContext because we don't have a scope.
1750 DeclContext *PreviousContext = CurContext;
1751 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001753 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001754 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001755 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001756 CurContext = PreviousContext;
1757
1758 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001759 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001760 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1761 assert(MSInfo && "Missing member specialization information?");
1762 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1763 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001764 DeclGroupRef DG(Var);
1765 Consumer.HandleTopLevelDecl(DG);
1766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Douglas Gregor7caa6822009-07-24 20:34:43 +00001768 if (Recursive) {
1769 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001771 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Douglas Gregor7caa6822009-07-24 20:34:43 +00001773 // Restore the set of pending implicit instantiations.
1774 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001775 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001776}
Douglas Gregor815215d2009-05-27 05:35:12 +00001777
Anders Carlsson09025312009-08-29 05:16:22 +00001778void
1779Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1780 const CXXConstructorDecl *Tmpl,
1781 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Anders Carlsson09025312009-08-29 05:16:22 +00001783 llvm::SmallVector<MemInitTy*, 4> NewInits;
1784
1785 // Instantiate all the initializers.
1786 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001787 InitsEnd = Tmpl->init_end();
1788 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001789 CXXBaseOrMemberInitializer *Init = *Inits;
1790
1791 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Anders Carlsson09025312009-08-29 05:16:22 +00001793 // Instantiate all the arguments.
1794 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1795 Args != ArgsEnd; ++Args) {
1796 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1797
1798 if (NewArg.isInvalid())
1799 New->setInvalidDecl();
1800 else
1801 NewArgs.push_back(NewArg.takeAs<Expr>());
1802 }
1803
1804 MemInitResult NewInit;
1805
1806 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001807 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001808 TemplateArgs,
1809 Init->getSourceLocation(),
1810 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001811 if (!BaseTInfo) {
Douglas Gregor802ab452009-12-02 22:36:29 +00001812 New->setInvalidDecl();
1813 continue;
1814 }
1815
John McCalla93c9342009-12-07 02:54:59 +00001816 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001817 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001818 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001819 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001820 Init->getRParenLoc(),
1821 New->getParent());
1822 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001823 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001825 // Is this an anonymous union?
1826 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001827 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001828 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001829 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1830 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001831
1832 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001833 NewArgs.size(),
1834 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001835 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001836 Init->getRParenLoc());
1837 }
1838
1839 if (NewInit.isInvalid())
1840 New->setInvalidDecl();
1841 else {
1842 // FIXME: It would be nice if ASTOwningVector had a release function.
1843 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Anders Carlsson09025312009-08-29 05:16:22 +00001845 NewInits.push_back((MemInitTy *)NewInit.get());
1846 }
1847 }
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Anders Carlsson09025312009-08-29 05:16:22 +00001849 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001850 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001851 /*FIXME: ColonLoc */
1852 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001853 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001854}
1855
John McCall52a575a2009-08-29 08:11:13 +00001856// TODO: this could be templated if the various decl types used the
1857// same method name.
1858static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1859 ClassTemplateDecl *Instance) {
1860 Pattern = Pattern->getCanonicalDecl();
1861
1862 do {
1863 Instance = Instance->getCanonicalDecl();
1864 if (Pattern == Instance) return true;
1865 Instance = Instance->getInstantiatedFromMemberTemplate();
1866 } while (Instance);
1867
1868 return false;
1869}
1870
Douglas Gregor0d696532009-09-28 06:34:35 +00001871static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1872 FunctionTemplateDecl *Instance) {
1873 Pattern = Pattern->getCanonicalDecl();
1874
1875 do {
1876 Instance = Instance->getCanonicalDecl();
1877 if (Pattern == Instance) return true;
1878 Instance = Instance->getInstantiatedFromMemberTemplate();
1879 } while (Instance);
1880
1881 return false;
1882}
1883
Douglas Gregored9c0f92009-10-29 00:04:11 +00001884static bool
1885isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1886 ClassTemplatePartialSpecializationDecl *Instance) {
1887 Pattern
1888 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1889 do {
1890 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1891 Instance->getCanonicalDecl());
1892 if (Pattern == Instance)
1893 return true;
1894 Instance = Instance->getInstantiatedFromMember();
1895 } while (Instance);
1896
1897 return false;
1898}
1899
John McCall52a575a2009-08-29 08:11:13 +00001900static bool isInstantiationOf(CXXRecordDecl *Pattern,
1901 CXXRecordDecl *Instance) {
1902 Pattern = Pattern->getCanonicalDecl();
1903
1904 do {
1905 Instance = Instance->getCanonicalDecl();
1906 if (Pattern == Instance) return true;
1907 Instance = Instance->getInstantiatedFromMemberClass();
1908 } while (Instance);
1909
1910 return false;
1911}
1912
1913static bool isInstantiationOf(FunctionDecl *Pattern,
1914 FunctionDecl *Instance) {
1915 Pattern = Pattern->getCanonicalDecl();
1916
1917 do {
1918 Instance = Instance->getCanonicalDecl();
1919 if (Pattern == Instance) return true;
1920 Instance = Instance->getInstantiatedFromMemberFunction();
1921 } while (Instance);
1922
1923 return false;
1924}
1925
1926static bool isInstantiationOf(EnumDecl *Pattern,
1927 EnumDecl *Instance) {
1928 Pattern = Pattern->getCanonicalDecl();
1929
1930 do {
1931 Instance = Instance->getCanonicalDecl();
1932 if (Pattern == Instance) return true;
1933 Instance = Instance->getInstantiatedFromMemberEnum();
1934 } while (Instance);
1935
1936 return false;
1937}
1938
John McCalled976492009-12-04 22:46:56 +00001939static bool isInstantiationOf(UsingShadowDecl *Pattern,
1940 UsingShadowDecl *Instance,
1941 ASTContext &C) {
1942 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1943}
1944
1945static bool isInstantiationOf(UsingDecl *Pattern,
1946 UsingDecl *Instance,
1947 ASTContext &C) {
1948 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1949}
1950
John McCall7ba107a2009-11-18 02:36:19 +00001951static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1952 UsingDecl *Instance,
1953 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001954 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00001955}
1956
1957static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001958 UsingDecl *Instance,
1959 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00001960 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001961}
1962
John McCall52a575a2009-08-29 08:11:13 +00001963static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1964 VarDecl *Instance) {
1965 assert(Instance->isStaticDataMember());
1966
1967 Pattern = Pattern->getCanonicalDecl();
1968
1969 do {
1970 Instance = Instance->getCanonicalDecl();
1971 if (Pattern == Instance) return true;
1972 Instance = Instance->getInstantiatedFromStaticDataMember();
1973 } while (Instance);
1974
1975 return false;
1976}
1977
John McCalled976492009-12-04 22:46:56 +00001978// Other is the prospective instantiation
1979// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00001980static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001981 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001982 if (UnresolvedUsingTypenameDecl *UUD
1983 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1984 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1985 return isInstantiationOf(UUD, UD, Ctx);
1986 }
1987 }
1988
1989 if (UnresolvedUsingValueDecl *UUD
1990 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001991 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1992 return isInstantiationOf(UUD, UD, Ctx);
1993 }
1994 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001995
Anders Carlsson0d8df782009-08-29 19:37:28 +00001996 return false;
1997 }
Mike Stump1eb44332009-09-09 15:08:12 +00001998
John McCall52a575a2009-08-29 08:11:13 +00001999 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2000 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
John McCall52a575a2009-08-29 08:11:13 +00002002 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2003 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002004
John McCall52a575a2009-08-29 08:11:13 +00002005 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2006 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002007
Douglas Gregor7caa6822009-07-24 20:34:43 +00002008 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002009 if (Var->isStaticDataMember())
2010 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2011
2012 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2013 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002014
Douglas Gregor0d696532009-09-28 06:34:35 +00002015 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2016 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2017
Douglas Gregored9c0f92009-10-29 00:04:11 +00002018 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2019 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2020 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2021 PartialSpec);
2022
Anders Carlssond8b285f2009-09-01 04:26:58 +00002023 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2024 if (!Field->getDeclName()) {
2025 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002026 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002027 cast<FieldDecl>(D);
2028 }
2029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
John McCalled976492009-12-04 22:46:56 +00002031 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2032 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2033
2034 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2035 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2036
Douglas Gregor815215d2009-05-27 05:35:12 +00002037 return D->getDeclName() && isa<NamedDecl>(Other) &&
2038 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2039}
2040
2041template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002042static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002043 NamedDecl *D,
2044 ForwardIterator first,
2045 ForwardIterator last) {
2046 for (; first != last; ++first)
2047 if (isInstantiationOf(Ctx, D, *first))
2048 return cast<NamedDecl>(*first);
2049
2050 return 0;
2051}
2052
John McCall02cace72009-08-28 07:59:38 +00002053/// \brief Finds the instantiation of the given declaration context
2054/// within the current instantiation.
2055///
2056/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00002057DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2058 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002059 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002060 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002061 return cast_or_null<DeclContext>(ID);
2062 } else return DC;
2063}
2064
Douglas Gregored961e72009-05-27 17:54:46 +00002065/// \brief Find the instantiation of the given declaration within the
2066/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002067///
2068/// This routine is intended to be used when \p D is a declaration
2069/// referenced from within a template, that needs to mapped into the
2070/// corresponding declaration within an instantiation. For example,
2071/// given:
2072///
2073/// \code
2074/// template<typename T>
2075/// struct X {
2076/// enum Kind {
2077/// KnownValue = sizeof(T)
2078/// };
2079///
2080/// bool getKind() const { return KnownValue; }
2081/// };
2082///
2083/// template struct X<int>;
2084/// \endcode
2085///
2086/// In the instantiation of X<int>::getKind(), we need to map the
2087/// EnumConstantDecl for KnownValue (which refers to
2088/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002089/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2090/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00002091NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2092 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002093 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002094 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2095 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2096 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002097 // D is a local of some kind. Look into the map of local
2098 // declarations to their instantiations.
2099 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2100 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002101
Douglas Gregore95b4092009-09-16 18:34:49 +00002102 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2103 if (!Record->isDependentContext())
2104 return D;
2105
2106 // If the RecordDecl is actually the injected-class-name or a "templated"
2107 // declaration for a class template or class template partial
2108 // specialization, substitute into the injected-class-name of the
2109 // class template or partial specialization to find the new DeclContext.
2110 QualType T;
2111 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2112
2113 if (ClassTemplate) {
2114 T = ClassTemplate->getInjectedClassNameType(Context);
2115 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2116 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2117 T = Context.getTypeDeclType(Record);
2118 ClassTemplate = PartialSpec->getSpecializedTemplate();
2119 }
2120
2121 if (!T.isNull()) {
2122 // Substitute into the injected-class-name to get the type corresponding
2123 // to the instantiation we want. This substitution should never fail,
2124 // since we know we can instantiate the injected-class-name or we wouldn't
2125 // have gotten to the injected-class-name!
2126 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2127 // instantiation in the common case?
2128 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2129 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2130
2131 if (!T->isDependentType()) {
2132 assert(T->isRecordType() && "Instantiation must produce a record type");
2133 return T->getAs<RecordType>()->getDecl();
2134 }
2135
2136 // We are performing "partial" template instantiation to create the
2137 // member declarations for the members of a class template
2138 // specialization. Therefore, D is actually referring to something in
2139 // the current instantiation. Look through the current context,
2140 // which contains actual instantiations, to find the instantiation of
2141 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00002142 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002143 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002144 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00002145 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002146 if (isInstantiationOf(ClassTemplate,
2147 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002148 return Spec;
2149 }
2150
Mike Stump1eb44332009-09-09 15:08:12 +00002151 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00002152 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00002153 return Record;
John McCall52a575a2009-08-29 08:11:13 +00002154 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002155
2156 // Fall through to deal with other dependent record types (e.g.,
2157 // anonymous unions in class templates).
2158 }
John McCall52a575a2009-08-29 08:11:13 +00002159
Douglas Gregore95b4092009-09-16 18:34:49 +00002160 if (!ParentDC->isDependentContext())
2161 return D;
2162
2163 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002164 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002165 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregor815215d2009-05-27 05:35:12 +00002167 if (ParentDC != D->getDeclContext()) {
2168 // We performed some kind of instantiation in the parent context,
2169 // so now we need to look into the instantiated parent context to
2170 // find the instantiation of the declaration D.
2171 NamedDecl *Result = 0;
2172 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002173 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002174 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2175 } else {
2176 // Since we don't have a name for the entity we're looking for,
2177 // our only option is to walk through all of the declarations to
2178 // find that name. This will occur in a few cases:
2179 //
2180 // - anonymous struct/union within a template
2181 // - unnamed class/struct/union/enum within a template
2182 //
2183 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002184 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002185 ParentDC->decls_begin(),
2186 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002187 }
Mike Stump1eb44332009-09-09 15:08:12 +00002188
John McCall9f54ad42009-12-10 09:41:52 +00002189 // UsingShadowDecls can instantiate to nothing because of using hiding.
2190 assert((Result || isa<UsingShadowDecl>(D))
2191 && "Unable to find instantiation of declaration!");
2192
Douglas Gregor815215d2009-05-27 05:35:12 +00002193 D = Result;
2194 }
2195
Douglas Gregor815215d2009-05-27 05:35:12 +00002196 return D;
2197}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002198
Mike Stump1eb44332009-09-09 15:08:12 +00002199/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002200/// instantiations we have seen until this point.
2201void Sema::PerformPendingImplicitInstantiations() {
2202 while (!PendingImplicitInstantiations.empty()) {
2203 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002204 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor7caa6822009-07-24 20:34:43 +00002206 // Instantiate function definitions
2207 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002208 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002209 Function->getLocation(), *this,
2210 Context.getSourceManager(),
2211 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002213 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002214 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002215 continue;
2216 }
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Douglas Gregor7caa6822009-07-24 20:34:43 +00002218 // Instantiate static data member definitions.
2219 VarDecl *Var = cast<VarDecl>(Inst.first);
2220 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002221
Mike Stump1eb44332009-09-09 15:08:12 +00002222 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002223 Var->getLocation(), *this,
2224 Context.getSourceManager(),
2225 "instantiating static data member "
2226 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Douglas Gregor7caa6822009-07-24 20:34:43 +00002228 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002229 }
2230}