blob: 3d9899e112eada1f01719cf1226ba3506754cf9e [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);
John McCall3dbd3d52010-02-16 06:53:13 +000046 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000048 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitFieldDecl(FieldDecl *D);
50 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
51 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000052 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000053 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000054 Decl *VisitFunctionDecl(FunctionDecl *D,
55 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000056 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000057 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
58 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000059 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000060 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000061 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000062 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000063 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000064 Decl *VisitClassTemplatePartialSpecializationDecl(
65 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000066 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000067 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000068 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000069 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000070 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000071 Decl *VisitUsingDecl(UsingDecl *D);
72 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000073 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
74 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor8dbc2692009-03-17 21:15:40 +000076 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000077 Decl *VisitDecl(Decl *D) {
78 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
79 Diagnostic::Error,
80 "cannot instantiate %0 yet");
81 SemaRef.Diag(D->getLocation(), DiagID)
82 << D->getDeclKindName();
83
Douglas Gregor8dbc2692009-03-17 21:15:40 +000084 return 0;
85 }
Douglas Gregor5545e162009-03-24 00:38:23 +000086
John McCallfd810b12009-08-14 02:03:10 +000087 const LangOptions &getLangOptions() {
88 return SemaRef.getLangOptions();
89 }
90
Douglas Gregor5545e162009-03-24 00:38:23 +000091 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000092 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000093 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000094 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000095 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000096
97 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000098 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000099
100 bool InstantiateClassTemplatePartialSpecialization(
101 ClassTemplateDecl *ClassTemplate,
102 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000103 };
104}
105
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000106// FIXME: Is this too simple?
107void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
108 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
109 TmplAttr = TmplAttr->getNext()) {
110
111 // FIXME: Is cloning correct for all attributes?
112 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
113
114 New->addAttr(NewAttr);
115 }
116}
117
Douglas Gregor4f722be2009-03-25 15:45:12 +0000118Decl *
119TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
120 assert(false && "Translation units cannot be instantiated");
121 return D;
122}
123
124Decl *
125TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
126 assert(false && "Namespaces cannot be instantiated");
127 return D;
128}
129
John McCall3dbd3d52010-02-16 06:53:13 +0000130Decl *
131TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
132 NamespaceAliasDecl *Inst
133 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
134 D->getNamespaceLoc(),
135 D->getAliasLoc(),
136 D->getNamespace()->getIdentifier(),
137 D->getQualifierRange(),
138 D->getQualifier(),
139 D->getTargetNameLoc(),
140 D->getNamespace());
141 Owner->addDecl(Inst);
142 return Inst;
143}
144
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
146 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000147 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000148 if (DI->getType()->isDependentType()) {
149 DI = SemaRef.SubstType(DI, TemplateArgs,
150 D->getLocation(), D->getDeclName());
151 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000152 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000153 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000154 }
155 }
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000157 // Create the new typedef
158 TypedefDecl *Typedef
159 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000160 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000161 if (Invalid)
162 Typedef->setInvalidDecl();
163
John McCall5126fd02009-12-30 00:31:22 +0000164 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000165 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
166 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000167 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
168 }
169
John McCall46460a62010-01-20 21:53:11 +0000170 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000171 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000173 return Typedef;
174}
175
Douglas Gregor6eef5192009-12-14 19:27:10 +0000176/// \brief Instantiate the arguments provided as part of initialization.
177///
178/// \returns true if an error occurred, false otherwise.
179static bool InstantiateInitializationArguments(Sema &SemaRef,
180 Expr **Args, unsigned NumArgs,
181 const MultiLevelTemplateArgumentList &TemplateArgs,
182 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
183 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
184 for (unsigned I = 0; I != NumArgs; ++I) {
185 // When we hit the first defaulted argument, break out of the loop:
186 // we don't pass those default arguments on.
187 if (Args[I]->isDefaultArgument())
188 break;
189
190 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
191 if (Arg.isInvalid())
192 return true;
193
194 Expr *ArgExpr = (Expr *)Arg.get();
195 InitArgs.push_back(Arg.release());
196
197 // FIXME: We're faking all of the comma locations. Do we need them?
198 FakeCommaLocs.push_back(
199 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
200 }
201
202 return false;
203}
204
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000205Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000206 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000207 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000208 TemplateArgs,
209 D->getTypeSpecStartLoc(),
210 D->getDeclName());
211 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000212 return 0;
213
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000214 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000215 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
216 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000217 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000218 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000219 Var->setThreadSpecified(D->isThreadSpecified());
220 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
221 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000222
223 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000224 // out-of-line, the instantiation will have the same lexical
225 // context (which will be a namespace scope) as the template.
226 if (D->isOutOfLine())
227 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000228
John McCall46460a62010-01-20 21:53:11 +0000229 Var->setAccess(D->getAccess());
230
Mike Stump390b4cc2009-05-16 07:39:55 +0000231 // FIXME: In theory, we could have a previous declaration for variables that
232 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000233 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000234 // FIXME: having to fake up a LookupResult is dumb.
235 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
236 Sema::LookupOrdinaryName);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000237 if (D->isStaticDataMember())
238 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000239 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Douglas Gregor7caa6822009-07-24 20:34:43 +0000241 if (D->isOutOfLine()) {
242 D->getLexicalDeclContext()->addDecl(Var);
243 Owner->makeDeclVisibleInContext(Var);
244 } else {
245 Owner->addDecl(Var);
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000248 // Link instantiations of static data members back to the template from
249 // which they were instantiated.
250 if (Var->isStaticDataMember())
251 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000252 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000253
Douglas Gregor60c93c92010-02-09 07:26:29 +0000254 if (Var->getAnyInitializer()) {
255 // We already have an initializer in the class.
256 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000257 if (Var->isStaticDataMember() && !D->isOutOfLine())
258 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
259 else
260 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
261
Douglas Gregor6eef5192009-12-14 19:27:10 +0000262 // Extract the initializer, skipping through any temporary-binding
263 // expressions and look at the subexpression as it was written.
264 Expr *DInit = D->getInit();
Douglas Gregora89ebea2010-02-03 09:01:59 +0000265 if (CXXExprWithTemporaries *ExprTemp
266 = dyn_cast<CXXExprWithTemporaries>(DInit))
267 DInit = ExprTemp->getSubExpr();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000268 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
269 DInit = Binder->getSubExpr();
270 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
271 DInit = ICE->getSubExprAsWritten();
272
273 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
274 // The initializer is a parenthesized list of expressions that is
275 // type-dependent. Instantiate each of the expressions; we'll be
276 // performing direct initialization with them.
277 llvm::SmallVector<SourceLocation, 4> CommaLocs;
278 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
279 if (!InstantiateInitializationArguments(SemaRef,
280 PLE->getExprs(),
281 PLE->getNumExprs(),
282 TemplateArgs,
283 CommaLocs, InitArgs)) {
284 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000285 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6eef5192009-12-14 19:27:10 +0000286 PLE->getLParenLoc(),
287 move_arg(InitArgs),
288 CommaLocs.data(),
289 PLE->getRParenLoc());
290 }
291 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
292 // The initializer resolved to a constructor. Instantiate the constructor
293 // arguments.
294 llvm::SmallVector<SourceLocation, 4> CommaLocs;
295 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
296
297 if (!InstantiateInitializationArguments(SemaRef,
298 Construct->getArgs(),
299 Construct->getNumArgs(),
300 TemplateArgs,
301 CommaLocs, InitArgs)) {
302 if (D->hasCXXDirectInitializer()) {
303 SourceLocation FakeLParenLoc =
304 SemaRef.PP.getLocForEndOfToken(D->getLocation());
305 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
306 : CommaLocs.back();
307 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
308 FakeLParenLoc,
309 move_arg(InitArgs),
310 CommaLocs.data(),
311 FakeRParenLoc);
312 } else if (InitArgs.size() == 1) {
313 Expr *Init = (Expr*)(InitArgs.take()[0]);
314 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
315 SemaRef.Owned(Init),
316 false);
317 } else {
318 assert(InitArgs.size() == 0);
319 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
320 }
321 }
322 } else {
323 OwningExprResult Init
324 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
325
326 // FIXME: Not happy about invalidating decls just because of a bad
327 // initializer, unless it affects the type.
328 if (Init.isInvalid())
329 Var->setInvalidDecl();
330 else
331 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
332 D->hasCXXDirectInitializer());
333 }
334
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000335 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000336 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
337 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000338
339 return Var;
340}
341
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000342Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
343 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000344 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000345 if (DI->getType()->isDependentType()) {
346 DI = SemaRef.SubstType(DI, TemplateArgs,
347 D->getLocation(), D->getDeclName());
348 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000349 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000350 Invalid = true;
351 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000352 // C++ [temp.arg.type]p3:
353 // If a declaration acquires a function type through a type
354 // dependent on a template-parameter and this causes a
355 // declaration that does not use the syntactic form of a
356 // function declarator to have function type, the program is
357 // ill-formed.
358 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000359 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000360 Invalid = true;
361 }
362 }
363
364 Expr *BitWidth = D->getBitWidth();
365 if (Invalid)
366 BitWidth = 0;
367 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000368 // The bit-width expression is not potentially evaluated.
369 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000371 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000372 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000373 if (InstantiatedBitWidth.isInvalid()) {
374 Invalid = true;
375 BitWidth = 0;
376 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000377 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000378 }
379
John McCall07fb6be2009-10-22 23:33:21 +0000380 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
381 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000382 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383 D->getLocation(),
384 D->isMutable(),
385 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000386 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000387 D->getAccess(),
388 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000389 if (!Field) {
390 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000391 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000392 }
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000394 InstantiateAttrs(D, Field);
395
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000396 if (Invalid)
397 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000399 if (!Field->getDeclName()) {
400 // Keep track of where this decl came from.
401 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000402 }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000404 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000405 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000406 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000407
408 return Field;
409}
410
John McCall02cace72009-08-28 07:59:38 +0000411Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
412 FriendDecl::FriendUnion FU;
413
414 // Handle friend type expressions by simply substituting template
415 // parameters into the pattern type.
416 if (Type *Ty = D->getFriendType()) {
417 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
418 D->getLocation(), DeclarationName());
419 if (T.isNull()) return 0;
420
421 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
422 FU = T.getTypePtr();
423
424 // Handle everything else by appropriate substitution.
425 } else {
426 NamedDecl *ND = D->getFriendDecl();
427 assert(ND && "friend decl must be a decl or a type!");
428
Douglas Gregora735b202009-10-13 14:39:41 +0000429 // FIXME: We have a problem here, because the nested call to Visit(ND)
430 // will inject the thing that the friend references into the current
431 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000432 Decl *NewND;
433
434 // Hack to make this work almost well pending a rewrite.
Douglas Gregor63644fa2010-02-07 10:31:35 +0000435 if (ND->getDeclContext()->isRecord()) {
436 if (!ND->getDeclContext()->isDependentContext()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000437 NewND = SemaRef.FindInstantiatedDecl(D->getLocation(), ND,
438 TemplateArgs);
Douglas Gregor63644fa2010-02-07 10:31:35 +0000439 } else {
440 // FIXME: Hack to avoid crashing when incorrectly trying to instantiate
441 // templated friend declarations. This doesn't produce a correct AST;
442 // however this is sufficient for some AST analysis. The real solution
443 // must be put in place during the pending rewrite. See PR5848.
444 return 0;
445 }
446 } else if (D->wasSpecialization()) {
Douglas Gregor7557a132009-12-24 20:56:24 +0000447 // Totally egregious hack to work around PR5866
448 return 0;
449 } else
John McCalle129d442009-12-17 23:21:11 +0000450 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000451 if (!NewND) return 0;
452
453 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
John McCall02cace72009-08-28 07:59:38 +0000456 FriendDecl *FD =
457 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
458 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000459 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000460 Owner->addDecl(FD);
461 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000462}
463
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000464Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
465 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Douglas Gregorac7610d2009-06-22 20:57:11 +0000467 // The expression in a static assertion is not potentially evaluated.
468 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000470 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000471 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000472 if (InstantiatedAssertExpr.isInvalid())
473 return 0;
474
Douglas Gregor43d9d922009-08-08 01:41:12 +0000475 OwningExprResult Message(SemaRef, D->getMessage());
476 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000477 Decl *StaticAssert
478 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000479 move(InstantiatedAssertExpr),
480 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000481 return StaticAssert;
482}
483
484Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000485 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000486 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000487 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000488 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000489 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000490 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000491 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000492 Enum->startDefinition();
493
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000494 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000495
496 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000497 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
498 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000499 EC != ECEnd; ++EC) {
500 // The specified value for the enumerator.
501 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000502 if (Expr *UninstValue = EC->getInitExpr()) {
503 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000504 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000505 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000506
John McCallce3ff2b2009-08-25 22:02:44 +0000507 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000508 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000509
510 // Drop the initial value and continue.
511 bool isInvalid = false;
512 if (Value.isInvalid()) {
513 Value = SemaRef.Owned((Expr *)0);
514 isInvalid = true;
515 }
516
Mike Stump1eb44332009-09-09 15:08:12 +0000517 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000518 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
519 EC->getLocation(), EC->getIdentifier(),
520 move(Value));
521
522 if (isInvalid) {
523 if (EnumConst)
524 EnumConst->setInvalidDecl();
525 Enum->setInvalidDecl();
526 }
527
528 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000529 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000530 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000531 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000532 LastEnumConst = EnumConst;
533 }
534 }
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000536 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000537 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000538 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
539 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000540 &Enumerators[0], Enumerators.size(),
541 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000542
543 return Enum;
544}
545
Douglas Gregor6477b692009-03-25 15:04:13 +0000546Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
547 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
548 return 0;
549}
550
Douglas Gregored9c0f92009-10-29 00:04:11 +0000551namespace {
552 class SortDeclByLocation {
553 SourceManager &SourceMgr;
554
555 public:
556 explicit SortDeclByLocation(SourceManager &SourceMgr)
557 : SourceMgr(SourceMgr) { }
558
559 bool operator()(const Decl *X, const Decl *Y) const {
560 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
561 Y->getLocation());
562 }
563 };
564}
565
John McCalle29ba202009-08-20 01:44:21 +0000566Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000567 // Create a local instantiation scope for this class template, which
568 // will contain the instantiations of the template parameters.
569 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000570 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000571 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000572 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000573 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000574
575 CXXRecordDecl *Pattern = D->getTemplatedDecl();
576 CXXRecordDecl *RecordInst
577 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
578 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000579 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
580 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000581
582 ClassTemplateDecl *Inst
583 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
584 D->getIdentifier(), InstParams, RecordInst, 0);
585 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000586 if (D->getFriendObjectKind())
587 Inst->setObjectOfFriendDecl(true);
588 else
589 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000590 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000591
592 // Trigger creation of the type for the instantiation.
593 SemaRef.Context.getTypeDeclType(RecordInst);
594
Douglas Gregor259571e2009-10-30 22:42:42 +0000595 // Finish handling of friends.
596 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000597 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000598 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000599
John McCall46460a62010-01-20 21:53:11 +0000600 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000601 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000602
603 // First, we sort the partial specializations by location, so
604 // that we instantiate them in the order they were declared.
605 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
606 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
607 P = D->getPartialSpecializations().begin(),
608 PEnd = D->getPartialSpecializations().end();
609 P != PEnd; ++P)
610 PartialSpecs.push_back(&*P);
611 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
612 SortDeclByLocation(SemaRef.SourceMgr));
613
614 // Instantiate all of the partial specializations of this member class
615 // template.
616 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
617 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
618
John McCalle29ba202009-08-20 01:44:21 +0000619 return Inst;
620}
621
Douglas Gregord60e1052009-08-27 16:57:43 +0000622Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000623TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
624 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000625 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
626
627 // Lookup the already-instantiated declaration in the instantiation
628 // of the class template and return that.
629 DeclContext::lookup_result Found
630 = Owner->lookup(ClassTemplate->getDeclName());
631 if (Found.first == Found.second)
632 return 0;
633
634 ClassTemplateDecl *InstClassTemplate
635 = dyn_cast<ClassTemplateDecl>(*Found.first);
636 if (!InstClassTemplate)
637 return 0;
638
639 Decl *DCanon = D->getCanonicalDecl();
640 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
641 P = InstClassTemplate->getPartialSpecializations().begin(),
642 PEnd = InstClassTemplate->getPartialSpecializations().end();
643 P != PEnd; ++P) {
644 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
645 return &*P;
646 }
647
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000648 return 0;
649}
650
651Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000652TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000653 // Create a local instantiation scope for this function template, which
654 // will contain the instantiations of the template parameters and then get
655 // merged with the local instantiation scope for the function template
656 // itself.
657 Sema::LocalInstantiationScope Scope(SemaRef);
658
Douglas Gregord60e1052009-08-27 16:57:43 +0000659 TemplateParameterList *TempParams = D->getTemplateParameters();
660 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000661 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000662 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000663
Douglas Gregora735b202009-10-13 14:39:41 +0000664 FunctionDecl *Instantiated = 0;
665 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
666 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
667 InstParams));
668 else
669 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
670 D->getTemplatedDecl(),
671 InstParams));
672
673 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000674 return 0;
675
John McCall46460a62010-01-20 21:53:11 +0000676 Instantiated->setAccess(D->getAccess());
677
Mike Stump1eb44332009-09-09 15:08:12 +0000678 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000679 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000680 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000681 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000682 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000683 assert(InstTemplate &&
684 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000685
686 // Link the instantiation back to the pattern *unless* this is a
687 // non-definition friend declaration.
688 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
689 !(InstTemplate->getFriendObjectKind() &&
690 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000691 InstTemplate->setInstantiatedFromMemberTemplate(D);
692
693 // Add non-friends into the owner.
694 if (!InstTemplate->getFriendObjectKind())
695 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000696 return InstTemplate;
697}
698
Douglas Gregord475b8d2009-03-25 21:17:03 +0000699Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
700 CXXRecordDecl *PrevDecl = 0;
701 if (D->isInjectedClassName())
702 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000703 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000704 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
705 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000706 TemplateArgs);
707 if (!Prev) return 0;
708 PrevDecl = cast<CXXRecordDecl>(Prev);
709 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000710
711 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000712 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000713 D->getLocation(), D->getIdentifier(),
714 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000715 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000716 // FIXME: Check against AS_none is an ugly hack to work around the issue that
717 // the tag decls introduced by friend class declarations don't have an access
718 // specifier. Remove once this area of the code gets sorted out.
719 if (D->getAccess() != AS_none)
720 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000721 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000722 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000723
John McCall02cace72009-08-28 07:59:38 +0000724 // If the original function was part of a friend declaration,
725 // inherit its namespace state.
726 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
727 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
728
Anders Carlssond8b285f2009-09-01 04:26:58 +0000729 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
730
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000731 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000732 return Record;
733}
734
John McCall02cace72009-08-28 07:59:38 +0000735/// Normal class members are of more specific types and therefore
736/// don't make it here. This function serves two purposes:
737/// 1) instantiating function templates
738/// 2) substituting friend declarations
739/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000740Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000741 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000742 // Check whether there is already a function template specialization for
743 // this declaration.
744 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
745 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000746 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000747 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000748 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000749 TemplateArgs.getInnermost().getFlatArgumentList(),
750 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000751 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000752
753 FunctionTemplateSpecializationInfo *Info
754 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000755 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Douglas Gregor127102b2009-06-29 20:59:39 +0000757 // If we already have a function template specialization, return it.
758 if (Info)
759 return Info->Function;
760 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Douglas Gregor79c22782010-01-16 20:21:20 +0000762 bool MergeWithParentScope = (TemplateParams != 0) ||
763 !(isa<Decl>(Owner) &&
764 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
765 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Douglas Gregore53060f2009-06-25 22:08:12 +0000767 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000768 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000769 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000770 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000771
John McCall68b6b872010-02-06 01:50:47 +0000772 // If we're instantiating a local function declaration, put the result
773 // in the owner; otherwise we need to find the instantiated context.
774 DeclContext *DC;
775 if (D->getDeclContext()->isFunctionOrMethod())
776 DC = Owner;
777 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000778 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
779 TemplateArgs);
John McCall68b6b872010-02-06 01:50:47 +0000780
John McCall02cace72009-08-28 07:59:38 +0000781 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000782 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000783 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000784 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000785 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000786 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Douglas Gregore53060f2009-06-25 22:08:12 +0000788 // Attach the parameters
789 for (unsigned P = 0; P < Params.size(); ++P)
790 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +0000791 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000792
Douglas Gregora735b202009-10-13 14:39:41 +0000793 if (TemplateParams) {
794 // Our resulting instantiation is actually a function template, since we
795 // are substituting only the outer template parameters. For example, given
796 //
797 // template<typename T>
798 // struct X {
799 // template<typename U> friend void f(T, U);
800 // };
801 //
802 // X<int> x;
803 //
804 // We are instantiating the friend function template "f" within X<int>,
805 // which means substituting int for T, but leaving "f" as a friend function
806 // template.
807 // Build the function template itself.
808 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
809 Function->getLocation(),
810 Function->getDeclName(),
811 TemplateParams, Function);
812 Function->setDescribedFunctionTemplate(FunctionTemplate);
813 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000814 } else if (FunctionTemplate) {
815 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +0000816 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +0000817 &TemplateArgs.getInnermost(),
818 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000819 }
Douglas Gregora735b202009-10-13 14:39:41 +0000820
Douglas Gregore53060f2009-06-25 22:08:12 +0000821 if (InitFunctionInstantiation(Function, D))
822 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Douglas Gregore53060f2009-06-25 22:08:12 +0000824 bool Redeclaration = false;
825 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000826
John McCall68263142009-11-18 22:49:29 +0000827 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
828 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
829
Douglas Gregora735b202009-10-13 14:39:41 +0000830 if (TemplateParams || !FunctionTemplate) {
831 // Look only into the namespace where the friend would be declared to
832 // find a previous declaration. This is the innermost enclosing namespace,
833 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000834 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000835
Douglas Gregora735b202009-10-13 14:39:41 +0000836 // In C++, the previous declaration we find might be a tag type
837 // (class or enum). In this case, the new declaration will hide the
838 // tag type. Note that this does does not apply if we're declaring a
839 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000840 if (Previous.isSingleTagDecl())
841 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000842 }
843
John McCall9f54ad42009-12-10 09:41:52 +0000844 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
845 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000846 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000847
Douglas Gregora735b202009-10-13 14:39:41 +0000848 // If the original function was part of a friend declaration,
849 // inherit its namespace state and add it to the owner.
850 NamedDecl *FromFriendD
851 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
852 if (FromFriendD->getFriendObjectKind()) {
853 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000854 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000855 if (TemplateParams) {
856 ToFriendD = cast<NamedDecl>(FunctionTemplate);
857 PrevDecl = FunctionTemplate->getPreviousDeclaration();
858 } else {
859 ToFriendD = Function;
860 PrevDecl = Function->getPreviousDeclaration();
861 }
862 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
863 if (!Owner->isDependentContext() && !PrevDecl)
864 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
865
866 if (!TemplateParams)
867 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
868 }
869
Douglas Gregore53060f2009-06-25 22:08:12 +0000870 return Function;
871}
872
Douglas Gregord60e1052009-08-27 16:57:43 +0000873Decl *
874TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
875 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000876 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
877 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000878 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000879 // We are creating a function template specialization from a function
880 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000881 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000882 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000883 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000884 TemplateArgs.getInnermost().getFlatArgumentList(),
885 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000886 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
888 FunctionTemplateSpecializationInfo *Info
889 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000890 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregor6b906862009-08-21 00:16:32 +0000892 // If we already have a function template specialization, return it.
893 if (Info)
894 return Info->Function;
895 }
896
Douglas Gregor79c22782010-01-16 20:21:20 +0000897 bool MergeWithParentScope = (TemplateParams != 0) ||
898 !(isa<Decl>(Owner) &&
899 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
900 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000901
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000902 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000903 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000904 if (T.isNull())
905 return 0;
906
907 // Build the instantiated method declaration.
908 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000909 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Douglas Gregordec06662009-08-21 18:42:58 +0000911 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000912 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000913 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
914 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
915 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000916 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
917 Constructor->getLocation(),
918 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000919 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000920 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000921 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000922 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
923 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
924 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
925 SemaRef.Context.getCanonicalType(ClassTy));
926 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
927 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000928 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000929 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000930 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000931 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000932 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000933 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
934 ConvTy);
935 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
936 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000937 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000938 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000939 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000940 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000941 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000942 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000943 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000944 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000945
Douglas Gregord60e1052009-08-27 16:57:43 +0000946 if (TemplateParams) {
947 // Our resulting instantiation is actually a function template, since we
948 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000949 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000950 // template<typename T>
951 // struct X {
952 // template<typename U> void f(T, U);
953 // };
954 //
955 // X<int> x;
956 //
957 // We are instantiating the member template "f" within X<int>, which means
958 // substituting int for T, but leaving "f" as a member function template.
959 // Build the function template itself.
960 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
961 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000962 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000963 TemplateParams, Method);
964 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000965 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000966 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000967 } else if (FunctionTemplate) {
968 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +0000969 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +0000970 &TemplateArgs.getInnermost(),
971 InsertPos);
972 } else {
973 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000974 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000975 }
976
Mike Stump1eb44332009-09-09 15:08:12 +0000977 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000978 // out-of-line, the instantiation will have the same lexical
979 // context (which will be a namespace scope) as the template.
980 if (D->isOutOfLine())
981 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Douglas Gregor5545e162009-03-24 00:38:23 +0000983 // Attach the parameters
984 for (unsigned P = 0; P < Params.size(); ++P)
985 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +0000986 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000987
988 if (InitMethodInstantiation(Method, D))
989 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000990
John McCall68263142009-11-18 22:49:29 +0000991 LookupResult Previous(SemaRef, Name, SourceLocation(),
992 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Douglas Gregord60e1052009-08-27 16:57:43 +0000994 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +0000995 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Douglas Gregordec06662009-08-21 18:42:58 +0000997 // In C++, the previous declaration we find might be a tag type
998 // (class or enum). In this case, the new declaration will hide the
999 // tag type. Note that this does does not apply if we're declaring a
1000 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001001 if (Previous.isSingleTagDecl())
1002 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001003 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001004
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001005 bool Redeclaration = false;
1006 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001007 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001008 /*FIXME:*/OverloadableAttrRequired);
1009
Douglas Gregor4ba31362009-12-01 17:24:26 +00001010 if (D->isPure())
1011 SemaRef.CheckPureMethod(Method, SourceRange());
1012
John McCall46460a62010-01-20 21:53:11 +00001013 Method->setAccess(D->getAccess());
1014
John McCall68263142009-11-18 22:49:29 +00001015 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +00001016 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +00001017 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001019 return Method;
1020}
1021
Douglas Gregor615c5d42009-03-24 16:43:20 +00001022Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001023 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001024}
1025
Douglas Gregor03b2b072009-03-24 00:15:49 +00001026Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001027 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001028}
1029
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001030Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001031 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001032}
1033
Douglas Gregor6477b692009-03-25 15:04:13 +00001034ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +00001035 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001036 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +00001037 if (DI) {
1038 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1039 D->getDeclName());
1040 if (DI) T = DI->getType();
1041 } else {
1042 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1043 D->getDeclName());
1044 DI = 0;
1045 }
1046
1047 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001048 return 0;
1049
John McCall58e46772009-10-23 21:48:59 +00001050 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001051
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001052 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001053 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001054 = ParmVarDecl::Create(SemaRef.Context,
1055 SemaRef.Context.getTranslationUnitDecl(),
1056 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001057 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001058
Anders Carlsson9351c172009-08-25 03:18:48 +00001059 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001060 if (D->hasUninstantiatedDefaultArg())
1061 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001062 else if (Expr *Arg = D->getDefaultArg())
1063 Param->setUninstantiatedDefaultArg(Arg);
1064
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001065 // Note: we don't try to instantiate function parameters until after
1066 // we've instantiated the function's type. Therefore, we don't have
1067 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001068 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001069 return Param;
1070}
1071
John McCalle29ba202009-08-20 01:44:21 +00001072Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1073 TemplateTypeParmDecl *D) {
1074 // TODO: don't always clone when decls are refcounted.
1075 const Type* T = D->getTypeForDecl();
1076 assert(T->isTemplateTypeParmType());
1077 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001078
John McCalle29ba202009-08-20 01:44:21 +00001079 TemplateTypeParmDecl *Inst =
1080 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001081 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001082 TTPT->getName(),
1083 D->wasDeclaredWithTypename(),
1084 D->isParameterPack());
1085
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001086 if (D->hasDefaultArgument())
1087 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001088
Douglas Gregor550d9b22009-10-31 17:21:17 +00001089 // Introduce this template parameter's instantiation into the instantiation
1090 // scope.
1091 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1092
John McCalle29ba202009-08-20 01:44:21 +00001093 return Inst;
1094}
1095
Douglas Gregor33642df2009-10-23 23:25:44 +00001096Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1097 NonTypeTemplateParmDecl *D) {
1098 // Substitute into the type of the non-type template parameter.
1099 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001100 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001101 if (DI) {
1102 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1103 D->getDeclName());
1104 if (DI) T = DI->getType();
1105 } else {
1106 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1107 D->getDeclName());
1108 DI = 0;
1109 }
1110 if (T.isNull())
1111 return 0;
1112
1113 // Check that this type is acceptable for a non-type template parameter.
1114 bool Invalid = false;
1115 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1116 if (T.isNull()) {
1117 T = SemaRef.Context.IntTy;
1118 Invalid = true;
1119 }
1120
1121 NonTypeTemplateParmDecl *Param
1122 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1123 D->getDepth() - 1, D->getPosition(),
1124 D->getIdentifier(), T, DI);
1125 if (Invalid)
1126 Param->setInvalidDecl();
1127
1128 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001129
1130 // Introduce this template parameter's instantiation into the instantiation
1131 // scope.
1132 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001133 return Param;
1134}
1135
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001136Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001137TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1138 TemplateTemplateParmDecl *D) {
1139 // Instantiate the template parameter list of the template template parameter.
1140 TemplateParameterList *TempParams = D->getTemplateParameters();
1141 TemplateParameterList *InstParams;
1142 {
1143 // Perform the actual substitution of template parameters within a new,
1144 // local instantiation scope.
1145 Sema::LocalInstantiationScope Scope(SemaRef);
1146 InstParams = SubstTemplateParams(TempParams);
1147 if (!InstParams)
1148 return NULL;
1149 }
1150
1151 // Build the template template parameter.
1152 TemplateTemplateParmDecl *Param
1153 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1154 D->getDepth() - 1, D->getPosition(),
1155 D->getIdentifier(), InstParams);
1156 Param->setDefaultArgument(D->getDefaultArgument());
1157
1158 // Introduce this template parameter's instantiation into the instantiation
1159 // scope.
1160 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1161
1162 return Param;
1163}
1164
Douglas Gregor48c32a72009-11-17 06:07:40 +00001165Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1166 // Using directives are never dependent, so they require no explicit
1167
1168 UsingDirectiveDecl *Inst
1169 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1170 D->getNamespaceKeyLocation(),
1171 D->getQualifierRange(), D->getQualifier(),
1172 D->getIdentLocation(),
1173 D->getNominatedNamespace(),
1174 D->getCommonAncestor());
1175 Owner->addDecl(Inst);
1176 return Inst;
1177}
1178
John McCalled976492009-12-04 22:46:56 +00001179Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1180 // The nested name specifier is non-dependent, so no transformation
1181 // is required.
1182
John McCall9f54ad42009-12-10 09:41:52 +00001183 // We only need to do redeclaration lookups if we're in a class
1184 // scope (in fact, it's not really even possible in non-class
1185 // scopes).
1186 bool CheckRedeclaration = Owner->isRecord();
1187
1188 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1189 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1190
John McCalled976492009-12-04 22:46:56 +00001191 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1192 D->getLocation(),
1193 D->getNestedNameRange(),
1194 D->getUsingLocation(),
1195 D->getTargetNestedNameDecl(),
1196 D->getDeclName(),
1197 D->isTypeName());
1198
1199 CXXScopeSpec SS;
1200 SS.setScopeRep(D->getTargetNestedNameDecl());
1201 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001202
1203 if (CheckRedeclaration) {
1204 Prev.setHideTags(false);
1205 SemaRef.LookupQualifiedName(Prev, Owner);
1206
1207 // Check for invalid redeclarations.
1208 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1209 D->isTypeName(), SS,
1210 D->getLocation(), Prev))
1211 NewUD->setInvalidDecl();
1212
1213 }
1214
1215 if (!NewUD->isInvalidDecl() &&
1216 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001217 D->getLocation()))
1218 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001219
John McCalled976492009-12-04 22:46:56 +00001220 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1221 NewUD->setAccess(D->getAccess());
1222 Owner->addDecl(NewUD);
1223
John McCall9f54ad42009-12-10 09:41:52 +00001224 // Don't process the shadow decls for an invalid decl.
1225 if (NewUD->isInvalidDecl())
1226 return NewUD;
1227
John McCall323c3102009-12-22 22:26:37 +00001228 bool isFunctionScope = Owner->isFunctionOrMethod();
1229
John McCall9f54ad42009-12-10 09:41:52 +00001230 // Process the shadow decls.
1231 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1232 I != E; ++I) {
1233 UsingShadowDecl *Shadow = *I;
1234 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001235 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1236 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001237 TemplateArgs));
1238
1239 if (CheckRedeclaration &&
1240 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1241 continue;
1242
1243 UsingShadowDecl *InstShadow
1244 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1245 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001246
1247 if (isFunctionScope)
1248 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001249 }
John McCalled976492009-12-04 22:46:56 +00001250
1251 return NewUD;
1252}
1253
1254Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001255 // Ignore these; we handle them in bulk when processing the UsingDecl.
1256 return 0;
John McCalled976492009-12-04 22:46:56 +00001257}
1258
John McCall7ba107a2009-11-18 02:36:19 +00001259Decl * TemplateDeclInstantiator
1260 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001261 NestedNameSpecifier *NNS =
1262 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1263 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001264 TemplateArgs);
1265 if (!NNS)
1266 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001268 CXXScopeSpec SS;
1269 SS.setRange(D->getTargetNestedNameRange());
1270 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
1272 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001273 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001274 D->getUsingLoc(), SS, D->getLocation(),
1275 D->getDeclName(), 0,
1276 /*instantiation*/ true,
1277 /*typename*/ true, D->getTypenameLoc());
1278 if (UD)
John McCalled976492009-12-04 22:46:56 +00001279 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1280
John McCall7ba107a2009-11-18 02:36:19 +00001281 return UD;
1282}
1283
1284Decl * TemplateDeclInstantiator
1285 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1286 NestedNameSpecifier *NNS =
1287 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1288 D->getTargetNestedNameRange(),
1289 TemplateArgs);
1290 if (!NNS)
1291 return 0;
1292
1293 CXXScopeSpec SS;
1294 SS.setRange(D->getTargetNestedNameRange());
1295 SS.setScopeRep(NNS);
1296
1297 NamedDecl *UD =
1298 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1299 D->getUsingLoc(), SS, D->getLocation(),
1300 D->getDeclName(), 0,
1301 /*instantiation*/ true,
1302 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001303 if (UD)
John McCalled976492009-12-04 22:46:56 +00001304 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1305
Anders Carlsson0d8df782009-08-29 19:37:28 +00001306 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001307}
1308
John McCallce3ff2b2009-08-25 22:02:44 +00001309Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001310 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001311 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001312 if (D->isInvalidDecl())
1313 return 0;
1314
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001315 return Instantiator.Visit(D);
1316}
1317
John McCalle29ba202009-08-20 01:44:21 +00001318/// \brief Instantiates a nested template parameter list in the current
1319/// instantiation context.
1320///
1321/// \param L The parameter list to instantiate
1322///
1323/// \returns NULL if there was an error
1324TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001325TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001326 // Get errors for all the parameters before bailing out.
1327 bool Invalid = false;
1328
1329 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001330 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001331 ParamVector Params;
1332 Params.reserve(N);
1333 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1334 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001335 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001336 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001337 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001338 }
1339
1340 // Clean up if we had an error.
1341 if (Invalid) {
1342 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1343 PI != PE; ++PI)
1344 if (*PI)
1345 (*PI)->Destroy(SemaRef.Context);
1346 return NULL;
1347 }
1348
1349 TemplateParameterList *InstL
1350 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1351 L->getLAngleLoc(), &Params.front(), N,
1352 L->getRAngleLoc());
1353 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001354}
John McCalle29ba202009-08-20 01:44:21 +00001355
Douglas Gregored9c0f92009-10-29 00:04:11 +00001356/// \brief Instantiate the declaration of a class template partial
1357/// specialization.
1358///
1359/// \param ClassTemplate the (instantiated) class template that is partially
1360// specialized by the instantiation of \p PartialSpec.
1361///
1362/// \param PartialSpec the (uninstantiated) class template partial
1363/// specialization that we are instantiating.
1364///
1365/// \returns true if there was an error, false otherwise.
1366bool
1367TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1368 ClassTemplateDecl *ClassTemplate,
1369 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001370 // Create a local instantiation scope for this class template partial
1371 // specialization, which will contain the instantiations of the template
1372 // parameters.
1373 Sema::LocalInstantiationScope Scope(SemaRef);
1374
Douglas Gregored9c0f92009-10-29 00:04:11 +00001375 // Substitute into the template parameters of the class template partial
1376 // specialization.
1377 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1378 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1379 if (!InstParams)
1380 return true;
1381
1382 // Substitute into the template arguments of the class template partial
1383 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001384 const TemplateArgumentLoc *PartialSpecTemplateArgs
1385 = PartialSpec->getTemplateArgsAsWritten();
1386 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1387
John McCalld5532b62009-11-23 01:53:49 +00001388 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001389 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001390 TemplateArgumentLoc Loc;
1391 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001392 return true;
John McCalld5532b62009-11-23 01:53:49 +00001393 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001394 }
1395
1396
1397 // Check that the template argument list is well-formed for this
1398 // class template.
1399 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1400 InstTemplateArgs.size());
1401 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1402 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001403 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001404 false,
1405 Converted))
1406 return true;
1407
1408 // Figure out where to insert this class template partial specialization
1409 // in the member template's set of class template partial specializations.
1410 llvm::FoldingSetNodeID ID;
1411 ClassTemplatePartialSpecializationDecl::Profile(ID,
1412 Converted.getFlatArguments(),
1413 Converted.flatSize(),
1414 SemaRef.Context);
1415 void *InsertPos = 0;
1416 ClassTemplateSpecializationDecl *PrevDecl
1417 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1418 InsertPos);
1419
1420 // Build the canonical type that describes the converted template
1421 // arguments of the class template partial specialization.
1422 QualType CanonType
1423 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1424 Converted.getFlatArguments(),
1425 Converted.flatSize());
1426
1427 // Build the fully-sugared type for this class template
1428 // specialization as the user wrote in the specialization
1429 // itself. This means that we'll pretty-print the type retrieved
1430 // from the specialization's declaration the way that the user
1431 // actually wrote the specialization, rather than formatting the
1432 // name based on the "canonical" representation used to store the
1433 // template arguments in the specialization.
1434 QualType WrittenTy
1435 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001436 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001437 CanonType);
1438
1439 if (PrevDecl) {
1440 // We've already seen a partial specialization with the same template
1441 // parameters and template arguments. This can happen, for example, when
1442 // substituting the outer template arguments ends up causing two
1443 // class template partial specializations of a member class template
1444 // to have identical forms, e.g.,
1445 //
1446 // template<typename T, typename U>
1447 // struct Outer {
1448 // template<typename X, typename Y> struct Inner;
1449 // template<typename Y> struct Inner<T, Y>;
1450 // template<typename Y> struct Inner<U, Y>;
1451 // };
1452 //
1453 // Outer<int, int> outer; // error: the partial specializations of Inner
1454 // // have the same signature.
1455 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1456 << WrittenTy;
1457 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1458 << SemaRef.Context.getTypeDeclType(PrevDecl);
1459 return true;
1460 }
1461
1462
1463 // Create the class template partial specialization declaration.
1464 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1465 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1466 PartialSpec->getLocation(),
1467 InstParams,
1468 ClassTemplate,
1469 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001470 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001471 0);
1472 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1473 InstPartialSpec->setTypeAsWritten(WrittenTy);
1474
1475 // Add this partial specialization to the set of class template partial
1476 // specializations.
1477 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1478 InsertPos);
1479 return false;
1480}
1481
John McCallce3ff2b2009-08-25 22:02:44 +00001482/// \brief Does substitution on the type of the given function, including
1483/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001484///
John McCallce3ff2b2009-08-25 22:02:44 +00001485/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001486///
1487/// \param Params the instantiated parameter declarations
1488
John McCallce3ff2b2009-08-25 22:02:44 +00001489/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001490/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001491QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001492TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001493 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1494 bool InvalidDecl = false;
1495
John McCallce3ff2b2009-08-25 22:02:44 +00001496 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001497 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001498 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001499 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001500 PEnd = D->param_end();
1501 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001502 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001503 if (PInst->getType()->isVoidType()) {
1504 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1505 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001506 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001507 PInst->getType(),
1508 diag::err_abstract_type_in_decl,
1509 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001510 PInst->setInvalidDecl();
1511
1512 Params.push_back(PInst);
1513 ParamTys.push_back(PInst->getType());
1514
1515 if (PInst->isInvalidDecl())
1516 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001517 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001518 InvalidDecl = true;
1519 }
1520
1521 // FIXME: Deallocate dead declarations.
1522 if (InvalidDecl)
1523 return QualType();
1524
John McCall183700f2009-09-21 23:43:11 +00001525 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001526 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001527 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001528 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1529 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001530 if (ResultType.isNull())
1531 return QualType();
1532
Jay Foadbeaaccd2009-05-21 09:52:38 +00001533 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001534 Proto->isVariadic(), Proto->getTypeQuals(),
1535 D->getLocation(), D->getDeclName());
1536}
1537
Mike Stump1eb44332009-09-09 15:08:12 +00001538/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001539/// declaration (New) from the corresponding fields of its template (Tmpl).
1540///
1541/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001542bool
1543TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001544 FunctionDecl *Tmpl) {
1545 if (Tmpl->isDeleted())
1546 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Douglas Gregorcca9e962009-07-01 22:01:06 +00001548 // If we are performing substituting explicitly-specified template arguments
1549 // or deduced template arguments into a function template and we reach this
1550 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001551 // to keeping the new function template specialization. We therefore
1552 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001553 // into a template instantiation for this specific function template
1554 // specialization, which is not a SFINAE context, so that we diagnose any
1555 // further errors in the declaration itself.
1556 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1557 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1558 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1559 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001560 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001561 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001562 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001563 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001564 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001565 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1566 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001567 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001568 }
1569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001571 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1572 assert(Proto && "Function template without prototype?");
1573
1574 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1575 Proto->getNoReturnAttr()) {
1576 // The function has an exception specification or a "noreturn"
1577 // attribute. Substitute into each of the exception types.
1578 llvm::SmallVector<QualType, 4> Exceptions;
1579 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1580 // FIXME: Poor location information!
1581 QualType T
1582 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1583 New->getLocation(), New->getDeclName());
1584 if (T.isNull() ||
1585 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1586 continue;
1587
1588 Exceptions.push_back(T);
1589 }
1590
1591 // Rebuild the function type
1592
1593 const FunctionProtoType *NewProto
1594 = New->getType()->getAs<FunctionProtoType>();
1595 assert(NewProto && "Template instantiation without function prototype?");
1596 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1597 NewProto->arg_type_begin(),
1598 NewProto->getNumArgs(),
1599 NewProto->isVariadic(),
1600 NewProto->getTypeQuals(),
1601 Proto->hasExceptionSpec(),
1602 Proto->hasAnyExceptionSpec(),
1603 Exceptions.size(),
1604 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001605 Proto->getNoReturnAttr(),
1606 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001607 }
1608
Douglas Gregore53060f2009-06-25 22:08:12 +00001609 return false;
1610}
1611
Douglas Gregor5545e162009-03-24 00:38:23 +00001612/// \brief Initializes common fields of an instantiated method
1613/// declaration (New) from the corresponding fields of its template
1614/// (Tmpl).
1615///
1616/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001617bool
1618TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001619 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001620 if (InitFunctionInstantiation(New, Tmpl))
1621 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Douglas Gregor5545e162009-03-24 00:38:23 +00001623 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1624 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001625 if (Tmpl->isVirtualAsWritten())
1626 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001627
1628 // FIXME: attributes
1629 // FIXME: New needs a pointer to Tmpl
1630 return false;
1631}
Douglas Gregora58861f2009-05-13 20:28:22 +00001632
1633/// \brief Instantiate the definition of the given function from its
1634/// template.
1635///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001636/// \param PointOfInstantiation the point at which the instantiation was
1637/// required. Note that this is not precisely a "point of instantiation"
1638/// for the function, but it's close.
1639///
Douglas Gregora58861f2009-05-13 20:28:22 +00001640/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001641/// function template specialization or member function of a class template
1642/// specialization.
1643///
1644/// \param Recursive if true, recursively instantiates any functions that
1645/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001646///
1647/// \param DefinitionRequired if true, then we are performing an explicit
1648/// instantiation where the body of the function is required. Complain if
1649/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001650void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001651 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001652 bool Recursive,
1653 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001654 if (Function->isInvalidDecl())
1655 return;
1656
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001657 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001659 // Never instantiate an explicit specialization.
1660 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1661 return;
1662
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001663 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001664 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001665 Stmt *Pattern = 0;
1666 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001667 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001668
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001669 if (!Pattern) {
1670 if (DefinitionRequired) {
1671 if (Function->getPrimaryTemplate())
1672 Diag(PointOfInstantiation,
1673 diag::err_explicit_instantiation_undefined_func_template)
1674 << Function->getPrimaryTemplate();
1675 else
1676 Diag(PointOfInstantiation,
1677 diag::err_explicit_instantiation_undefined_member)
1678 << 1 << Function->getDeclName() << Function->getDeclContext();
1679
1680 if (PatternDecl)
1681 Diag(PatternDecl->getLocation(),
1682 diag::note_explicit_instantiation_here);
1683 }
1684
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001685 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001686 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001687
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001688 // C++0x [temp.explicit]p9:
1689 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001690 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001691 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001692 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001693 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001694 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001695 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001697 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1698 if (Inst)
1699 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001700
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001701 // If we're performing recursive template instantiation, create our own
1702 // queue of pending implicit instantiations that we will instantiate later,
1703 // while we're still within our own instantiation context.
1704 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1705 if (Recursive)
1706 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001708 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1709
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001710 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001711 // recorded, unless we're actually a member function within a local
1712 // class, in which case we need to merge our results with the parent
1713 // scope (of the enclosing function).
1714 bool MergeWithParentScope = false;
1715 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1716 MergeWithParentScope = Rec->isLocalClass();
1717
1718 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001720 // Introduce the instantiated function parameters into the local
1721 // instantiation scope.
1722 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1723 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1724 Function->getParamDecl(I));
1725
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001726 // Enter the scope of this instantiation. We don't use
1727 // PushDeclContext because we don't have a scope.
1728 DeclContext *PreviousContext = CurContext;
1729 CurContext = Function;
1730
Mike Stump1eb44332009-09-09 15:08:12 +00001731 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001732 getTemplateInstantiationArgs(Function);
1733
1734 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001735 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001736 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1737 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1738 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001739 }
1740
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001741 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001742 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001743
Douglas Gregor52604ab2009-09-11 21:19:12 +00001744 if (Body.isInvalid())
1745 Function->setInvalidDecl();
1746
Mike Stump1eb44332009-09-09 15:08:12 +00001747 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001748 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001749
1750 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001751
1752 DeclGroupRef DG(Function);
1753 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Douglas Gregor60406be2010-01-16 22:29:39 +00001755 // This class may have local implicit instantiations that need to be
1756 // instantiation within this scope.
1757 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1758 Scope.Exit();
1759
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001760 if (Recursive) {
1761 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001762 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001763 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001765 // Restore the set of pending implicit instantiations.
1766 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1767 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001768}
1769
1770/// \brief Instantiate the definition of the given variable from its
1771/// template.
1772///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001773/// \param PointOfInstantiation the point at which the instantiation was
1774/// required. Note that this is not precisely a "point of instantiation"
1775/// for the function, but it's close.
1776///
1777/// \param Var the already-instantiated declaration of a static member
1778/// variable of a class template specialization.
1779///
1780/// \param Recursive if true, recursively instantiates any functions that
1781/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001782///
1783/// \param DefinitionRequired if true, then we are performing an explicit
1784/// instantiation where an out-of-line definition of the member variable
1785/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001786void Sema::InstantiateStaticDataMemberDefinition(
1787 SourceLocation PointOfInstantiation,
1788 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001789 bool Recursive,
1790 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001791 if (Var->isInvalidDecl())
1792 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Douglas Gregor7caa6822009-07-24 20:34:43 +00001794 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001795 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001796 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001797 assert(Def->isStaticDataMember() && "Not a static data member?");
1798 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Douglas Gregor0d035142009-10-27 18:42:08 +00001800 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001801 // We did not find an out-of-line definition of this static data member,
1802 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001803 // instantiate this definition (or provide a specialization for it) in
1804 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001805 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001806 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001807 Diag(PointOfInstantiation,
1808 diag::err_explicit_instantiation_undefined_member)
1809 << 2 << Var->getDeclName() << Var->getDeclContext();
1810 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1811 }
1812
Douglas Gregor7caa6822009-07-24 20:34:43 +00001813 return;
1814 }
1815
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001816 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001817 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001818 return;
1819
1820 // C++0x [temp.explicit]p9:
1821 // Except for inline functions, other explicit instantiation declarations
1822 // have the effect of suppressing the implicit instantiation of the entity
1823 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001824 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001825 == TSK_ExplicitInstantiationDeclaration)
1826 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Douglas Gregor7caa6822009-07-24 20:34:43 +00001828 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1829 if (Inst)
1830 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Douglas Gregor7caa6822009-07-24 20:34:43 +00001832 // If we're performing recursive template instantiation, create our own
1833 // queue of pending implicit instantiations that we will instantiate later,
1834 // while we're still within our own instantiation context.
1835 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1836 if (Recursive)
1837 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor7caa6822009-07-24 20:34:43 +00001839 // Enter the scope of this instantiation. We don't use
1840 // PushDeclContext because we don't have a scope.
1841 DeclContext *PreviousContext = CurContext;
1842 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001844 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001845 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001846 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001847 CurContext = PreviousContext;
1848
1849 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00001850 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1851 assert(MSInfo && "Missing member specialization information?");
1852 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1853 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001854 DeclGroupRef DG(Var);
1855 Consumer.HandleTopLevelDecl(DG);
1856 }
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Douglas Gregor7caa6822009-07-24 20:34:43 +00001858 if (Recursive) {
1859 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001860 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001861 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor7caa6822009-07-24 20:34:43 +00001863 // Restore the set of pending implicit instantiations.
1864 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001865 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001866}
Douglas Gregor815215d2009-05-27 05:35:12 +00001867
Anders Carlsson09025312009-08-29 05:16:22 +00001868void
1869Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1870 const CXXConstructorDecl *Tmpl,
1871 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Anders Carlsson09025312009-08-29 05:16:22 +00001873 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001874 bool AnyErrors = false;
1875
Anders Carlsson09025312009-08-29 05:16:22 +00001876 // Instantiate all the initializers.
1877 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001878 InitsEnd = Tmpl->init_end();
1879 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001880 CXXBaseOrMemberInitializer *Init = *Inits;
1881
1882 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001883 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Anders Carlsson09025312009-08-29 05:16:22 +00001885 // Instantiate all the arguments.
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001886 Expr *InitE = Init->getInit();
1887 if (!InitE) {
1888 // Nothing to instantiate;
1889 } else if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(InitE)) {
1890 if (InstantiateInitializationArguments(*this, ParenList->getExprs(),
1891 ParenList->getNumExprs(),
1892 TemplateArgs, CommaLocs,
1893 NewArgs)) {
1894 AnyErrors = true;
1895 continue;
1896 }
1897 } else {
1898 OwningExprResult InitArg = SubstExpr(InitE, TemplateArgs);
1899 if (InitArg.isInvalid()) {
1900 AnyErrors = true;
1901 continue;
1902 }
1903
1904 NewArgs.push_back(InitArg.release());
Anders Carlsson09025312009-08-29 05:16:22 +00001905 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001906
Anders Carlsson09025312009-08-29 05:16:22 +00001907 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00001908 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001909 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001910 TemplateArgs,
1911 Init->getSourceLocation(),
1912 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001913 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001914 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00001915 New->setInvalidDecl();
1916 continue;
1917 }
1918
John McCalla93c9342009-12-07 02:54:59 +00001919 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001920 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001921 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001922 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001923 Init->getRParenLoc(),
1924 New->getParent());
1925 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001926 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001928 // Is this an anonymous union?
1929 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001930 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1931 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001932 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001933 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1934 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00001935 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001936
1937 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001938 NewArgs.size(),
1939 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001940 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001941 Init->getRParenLoc());
1942 }
1943
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001944 if (NewInit.isInvalid()) {
1945 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00001946 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001947 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00001948 // FIXME: It would be nice if ASTOwningVector had a release function.
1949 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Anders Carlsson09025312009-08-29 05:16:22 +00001951 NewInits.push_back((MemInitTy *)NewInit.get());
1952 }
1953 }
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Anders Carlsson09025312009-08-29 05:16:22 +00001955 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001956 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001957 /*FIXME: ColonLoc */
1958 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001959 NewInits.data(), NewInits.size(),
1960 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00001961}
1962
John McCall52a575a2009-08-29 08:11:13 +00001963// TODO: this could be templated if the various decl types used the
1964// same method name.
1965static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1966 ClassTemplateDecl *Instance) {
1967 Pattern = Pattern->getCanonicalDecl();
1968
1969 do {
1970 Instance = Instance->getCanonicalDecl();
1971 if (Pattern == Instance) return true;
1972 Instance = Instance->getInstantiatedFromMemberTemplate();
1973 } while (Instance);
1974
1975 return false;
1976}
1977
Douglas Gregor0d696532009-09-28 06:34:35 +00001978static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1979 FunctionTemplateDecl *Instance) {
1980 Pattern = Pattern->getCanonicalDecl();
1981
1982 do {
1983 Instance = Instance->getCanonicalDecl();
1984 if (Pattern == Instance) return true;
1985 Instance = Instance->getInstantiatedFromMemberTemplate();
1986 } while (Instance);
1987
1988 return false;
1989}
1990
Douglas Gregored9c0f92009-10-29 00:04:11 +00001991static bool
1992isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1993 ClassTemplatePartialSpecializationDecl *Instance) {
1994 Pattern
1995 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1996 do {
1997 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1998 Instance->getCanonicalDecl());
1999 if (Pattern == Instance)
2000 return true;
2001 Instance = Instance->getInstantiatedFromMember();
2002 } while (Instance);
2003
2004 return false;
2005}
2006
John McCall52a575a2009-08-29 08:11:13 +00002007static bool isInstantiationOf(CXXRecordDecl *Pattern,
2008 CXXRecordDecl *Instance) {
2009 Pattern = Pattern->getCanonicalDecl();
2010
2011 do {
2012 Instance = Instance->getCanonicalDecl();
2013 if (Pattern == Instance) return true;
2014 Instance = Instance->getInstantiatedFromMemberClass();
2015 } while (Instance);
2016
2017 return false;
2018}
2019
2020static bool isInstantiationOf(FunctionDecl *Pattern,
2021 FunctionDecl *Instance) {
2022 Pattern = Pattern->getCanonicalDecl();
2023
2024 do {
2025 Instance = Instance->getCanonicalDecl();
2026 if (Pattern == Instance) return true;
2027 Instance = Instance->getInstantiatedFromMemberFunction();
2028 } while (Instance);
2029
2030 return false;
2031}
2032
2033static bool isInstantiationOf(EnumDecl *Pattern,
2034 EnumDecl *Instance) {
2035 Pattern = Pattern->getCanonicalDecl();
2036
2037 do {
2038 Instance = Instance->getCanonicalDecl();
2039 if (Pattern == Instance) return true;
2040 Instance = Instance->getInstantiatedFromMemberEnum();
2041 } while (Instance);
2042
2043 return false;
2044}
2045
John McCalled976492009-12-04 22:46:56 +00002046static bool isInstantiationOf(UsingShadowDecl *Pattern,
2047 UsingShadowDecl *Instance,
2048 ASTContext &C) {
2049 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2050}
2051
2052static bool isInstantiationOf(UsingDecl *Pattern,
2053 UsingDecl *Instance,
2054 ASTContext &C) {
2055 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2056}
2057
John McCall7ba107a2009-11-18 02:36:19 +00002058static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2059 UsingDecl *Instance,
2060 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002061 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002062}
2063
2064static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002065 UsingDecl *Instance,
2066 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002067 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002068}
2069
John McCall52a575a2009-08-29 08:11:13 +00002070static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2071 VarDecl *Instance) {
2072 assert(Instance->isStaticDataMember());
2073
2074 Pattern = Pattern->getCanonicalDecl();
2075
2076 do {
2077 Instance = Instance->getCanonicalDecl();
2078 if (Pattern == Instance) return true;
2079 Instance = Instance->getInstantiatedFromStaticDataMember();
2080 } while (Instance);
2081
2082 return false;
2083}
2084
John McCalled976492009-12-04 22:46:56 +00002085// Other is the prospective instantiation
2086// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002087static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002088 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002089 if (UnresolvedUsingTypenameDecl *UUD
2090 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2091 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2092 return isInstantiationOf(UUD, UD, Ctx);
2093 }
2094 }
2095
2096 if (UnresolvedUsingValueDecl *UUD
2097 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002098 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2099 return isInstantiationOf(UUD, UD, Ctx);
2100 }
2101 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002102
Anders Carlsson0d8df782009-08-29 19:37:28 +00002103 return false;
2104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
John McCall52a575a2009-08-29 08:11:13 +00002106 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2107 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002108
John McCall52a575a2009-08-29 08:11:13 +00002109 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2110 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002111
John McCall52a575a2009-08-29 08:11:13 +00002112 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2113 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002114
Douglas Gregor7caa6822009-07-24 20:34:43 +00002115 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002116 if (Var->isStaticDataMember())
2117 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2118
2119 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2120 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002121
Douglas Gregor0d696532009-09-28 06:34:35 +00002122 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2123 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2124
Douglas Gregored9c0f92009-10-29 00:04:11 +00002125 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2126 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2127 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2128 PartialSpec);
2129
Anders Carlssond8b285f2009-09-01 04:26:58 +00002130 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2131 if (!Field->getDeclName()) {
2132 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002133 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002134 cast<FieldDecl>(D);
2135 }
2136 }
Mike Stump1eb44332009-09-09 15:08:12 +00002137
John McCalled976492009-12-04 22:46:56 +00002138 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2139 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2140
2141 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2142 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2143
Douglas Gregor815215d2009-05-27 05:35:12 +00002144 return D->getDeclName() && isa<NamedDecl>(Other) &&
2145 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2146}
2147
2148template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002149static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002150 NamedDecl *D,
2151 ForwardIterator first,
2152 ForwardIterator last) {
2153 for (; first != last; ++first)
2154 if (isInstantiationOf(Ctx, D, *first))
2155 return cast<NamedDecl>(*first);
2156
2157 return 0;
2158}
2159
John McCall02cace72009-08-28 07:59:38 +00002160/// \brief Finds the instantiation of the given declaration context
2161/// within the current instantiation.
2162///
2163/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002164DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002165 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002166 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002167 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002168 return cast_or_null<DeclContext>(ID);
2169 } else return DC;
2170}
2171
Douglas Gregored961e72009-05-27 17:54:46 +00002172/// \brief Find the instantiation of the given declaration within the
2173/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002174///
2175/// This routine is intended to be used when \p D is a declaration
2176/// referenced from within a template, that needs to mapped into the
2177/// corresponding declaration within an instantiation. For example,
2178/// given:
2179///
2180/// \code
2181/// template<typename T>
2182/// struct X {
2183/// enum Kind {
2184/// KnownValue = sizeof(T)
2185/// };
2186///
2187/// bool getKind() const { return KnownValue; }
2188/// };
2189///
2190/// template struct X<int>;
2191/// \endcode
2192///
2193/// In the instantiation of X<int>::getKind(), we need to map the
2194/// EnumConstantDecl for KnownValue (which refers to
2195/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002196/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2197/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002198NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002199 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002200 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002201 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002202 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002203 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002204 // D is a local of some kind. Look into the map of local
2205 // declarations to their instantiations.
2206 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2207 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002208
Douglas Gregore95b4092009-09-16 18:34:49 +00002209 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2210 if (!Record->isDependentContext())
2211 return D;
2212
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002213 // If the RecordDecl is actually the injected-class-name or a
2214 // "templated" declaration for a class template, class template
2215 // partial specialization, or a member class of a class template,
2216 // substitute into the injected-class-name of the class template
2217 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002218 QualType T;
2219 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2220
2221 if (ClassTemplate) {
2222 T = ClassTemplate->getInjectedClassNameType(Context);
2223 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2224 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2225 T = Context.getTypeDeclType(Record);
2226 ClassTemplate = PartialSpec->getSpecializedTemplate();
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002227 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002228
2229 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002230 // Substitute into the injected-class-name to get the type
2231 // corresponding to the instantiation we want, which may also be
2232 // the current instantiation (if we're in a template
2233 // definition). This substitution should never fail, since we
2234 // know we can instantiate the injected-class-name or we
2235 // wouldn't have gotten to the injected-class-name!
2236
2237 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2238 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002239 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2240 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2241
2242 if (!T->isDependentType()) {
2243 assert(T->isRecordType() && "Instantiation must produce a record type");
2244 return T->getAs<RecordType>()->getDecl();
2245 }
2246
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002247 // We are performing "partial" template instantiation to create
2248 // the member declarations for the members of a class template
2249 // specialization. Therefore, D is actually referring to something
2250 // in the current instantiation. Look through the current
2251 // context, which contains actual instantiations, to find the
2252 // instantiation of the "current instantiation" that D refers
2253 // to.
2254 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002255 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002256 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002257 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002258 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002259 if (isInstantiationOf(ClassTemplate,
2260 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002261 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002262
2263 if (!DC->isDependentContext())
2264 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002265 }
2266
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002267 // We're performing "instantiation" of a member of the current
2268 // instantiation while we are type-checking the
2269 // definition. Compute the declaration context and return that.
2270 assert(!SawNonDependentContext &&
2271 "No dependent context while instantiating record");
2272 DeclContext *DC = computeDeclContext(T);
2273 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002274 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002275 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002276 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002277
Douglas Gregore95b4092009-09-16 18:34:49 +00002278 // Fall through to deal with other dependent record types (e.g.,
2279 // anonymous unions in class templates).
2280 }
John McCall52a575a2009-08-29 08:11:13 +00002281
Douglas Gregore95b4092009-09-16 18:34:49 +00002282 if (!ParentDC->isDependentContext())
2283 return D;
2284
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002285 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002286 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002287 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Douglas Gregor815215d2009-05-27 05:35:12 +00002289 if (ParentDC != D->getDeclContext()) {
2290 // We performed some kind of instantiation in the parent context,
2291 // so now we need to look into the instantiated parent context to
2292 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002293
2294 // If our context is a class template specialization, we may need
2295 // to instantiate it before performing lookup into that context.
2296 if (ClassTemplateSpecializationDecl *Spec
2297 = dyn_cast<ClassTemplateSpecializationDecl>(ParentDC)) {
2298 if (!Spec->isDependentContext()) {
2299 QualType T = Context.getTypeDeclType(Spec);
2300 if (const TagType *Tag = T->getAs<TagType>())
2301 if (!Tag->isBeingDefined() &&
2302 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2303 return 0;
2304 }
2305 }
2306
Douglas Gregor815215d2009-05-27 05:35:12 +00002307 NamedDecl *Result = 0;
2308 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002309 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002310 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2311 } else {
2312 // Since we don't have a name for the entity we're looking for,
2313 // our only option is to walk through all of the declarations to
2314 // find that name. This will occur in a few cases:
2315 //
2316 // - anonymous struct/union within a template
2317 // - unnamed class/struct/union/enum within a template
2318 //
2319 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002320 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002321 ParentDC->decls_begin(),
2322 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002323 }
Mike Stump1eb44332009-09-09 15:08:12 +00002324
John McCall9f54ad42009-12-10 09:41:52 +00002325 // UsingShadowDecls can instantiate to nothing because of using hiding.
2326 assert((Result || isa<UsingShadowDecl>(D))
2327 && "Unable to find instantiation of declaration!");
2328
Douglas Gregor815215d2009-05-27 05:35:12 +00002329 D = Result;
2330 }
2331
Douglas Gregor815215d2009-05-27 05:35:12 +00002332 return D;
2333}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002334
Mike Stump1eb44332009-09-09 15:08:12 +00002335/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002336/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002337void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2338 while (!PendingLocalImplicitInstantiations.empty() ||
2339 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2340 PendingImplicitInstantiation Inst;
2341
2342 if (PendingLocalImplicitInstantiations.empty()) {
2343 Inst = PendingImplicitInstantiations.front();
2344 PendingImplicitInstantiations.pop_front();
2345 } else {
2346 Inst = PendingLocalImplicitInstantiations.front();
2347 PendingLocalImplicitInstantiations.pop_front();
2348 }
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Douglas Gregor7caa6822009-07-24 20:34:43 +00002350 // Instantiate function definitions
2351 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002352 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002353 Function->getLocation(), *this,
2354 Context.getSourceManager(),
2355 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002356
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002357 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002358 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002359 continue;
2360 }
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor7caa6822009-07-24 20:34:43 +00002362 // Instantiate static data member definitions.
2363 VarDecl *Var = cast<VarDecl>(Inst.first);
2364 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002365
Chandler Carruth291b4412010-02-13 10:17:50 +00002366 // Don't try to instantiate declarations if the most recent redeclaration
2367 // is invalid.
2368 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2369 continue;
2370
2371 // Check if the most recent declaration has changed the specialization kind
2372 // and removed the need for implicit instantiation.
2373 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2374 case TSK_Undeclared:
2375 assert(false && "Cannot instantitiate an undeclared specialization.");
2376 case TSK_ExplicitInstantiationDeclaration:
2377 case TSK_ExplicitInstantiationDefinition:
2378 case TSK_ExplicitSpecialization:
2379 continue; // No longer need implicit instantiation.
2380 case TSK_ImplicitInstantiation:
2381 break;
2382 }
2383
Mike Stump1eb44332009-09-09 15:08:12 +00002384 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002385 Var->getLocation(), *this,
2386 Context.getSourceManager(),
2387 "instantiating static data member "
2388 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor7caa6822009-07-24 20:34:43 +00002390 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002391 }
2392}