blob: dbe041c4aadeed9f91cccd867954d1efc2b5d379 [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"
John McCall21ef0fa2010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000021#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000022#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000023
24using namespace clang;
25
26namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000027 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000028 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000029 Sema &SemaRef;
30 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000031 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Anders Carlssond8fe2d52009-11-07 06:07:58 +000033 void InstantiateAttrs(Decl *Tmpl, Decl *New);
34
Douglas Gregor8dbc2692009-03-17 21:15:40 +000035 public:
36 typedef Sema::OwningExprResult OwningExprResult;
37
38 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000039 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000040 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000041
Mike Stump390b4cc2009-05-16 07:39:55 +000042 // FIXME: Once we get closer to completion, replace these manually-written
43 // declarations with automatically-generated ones from
44 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000045 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
46 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000047 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000049 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000050 Decl *VisitFieldDecl(FieldDecl *D);
51 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
52 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000053 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000054 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000055 Decl *VisitFunctionDecl(FunctionDecl *D,
56 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000057 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000058 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
59 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000060 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000061 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000062 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000063 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000064 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000065 Decl *VisitClassTemplatePartialSpecializationDecl(
66 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000067 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000068 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000069 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000070 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000071 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000072 Decl *VisitUsingDecl(UsingDecl *D);
73 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000074 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
75 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Douglas Gregor8dbc2692009-03-17 21:15:40 +000077 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000078 Decl *VisitDecl(Decl *D) {
79 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
80 Diagnostic::Error,
81 "cannot instantiate %0 yet");
82 SemaRef.Diag(D->getLocation(), DiagID)
83 << D->getDeclKindName();
84
Douglas Gregor8dbc2692009-03-17 21:15:40 +000085 return 0;
86 }
Douglas Gregor5545e162009-03-24 00:38:23 +000087
John McCallfd810b12009-08-14 02:03:10 +000088 const LangOptions &getLangOptions() {
89 return SemaRef.getLangOptions();
90 }
91
Douglas Gregor5545e162009-03-24 00:38:23 +000092 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000093 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000094 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000095 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000096 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000097
98 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000099 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000100
101 bool SubstQualifier(const DeclaratorDecl *OldDecl,
102 DeclaratorDecl *NewDecl);
103 bool SubstQualifier(const TagDecl *OldDecl,
104 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000105
106 bool InstantiateClassTemplatePartialSpecialization(
107 ClassTemplateDecl *ClassTemplate,
108 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000109 };
110}
111
John McCallb6217662010-03-15 10:12:16 +0000112bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
113 DeclaratorDecl *NewDecl) {
114 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
115 if (!OldQual) return false;
116
117 SourceRange QualRange = OldDecl->getQualifierRange();
118
119 NestedNameSpecifier *NewQual
120 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
121 if (!NewQual)
122 return true;
123
124 NewDecl->setQualifierInfo(NewQual, QualRange);
125 return false;
126}
127
128bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
129 TagDecl *NewDecl) {
130 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
131 if (!OldQual) return false;
132
133 SourceRange QualRange = OldDecl->getQualifierRange();
134
135 NestedNameSpecifier *NewQual
136 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
137 if (!NewQual)
138 return true;
139
140 NewDecl->setQualifierInfo(NewQual, QualRange);
141 return false;
142}
143
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000144// FIXME: Is this too simple?
145void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
146 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
147 TmplAttr = TmplAttr->getNext()) {
148
149 // FIXME: Is cloning correct for all attributes?
150 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
151
152 New->addAttr(NewAttr);
153 }
154}
155
Douglas Gregor4f722be2009-03-25 15:45:12 +0000156Decl *
157TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
158 assert(false && "Translation units cannot be instantiated");
159 return D;
160}
161
162Decl *
163TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
164 assert(false && "Namespaces cannot be instantiated");
165 return D;
166}
167
John McCall3dbd3d52010-02-16 06:53:13 +0000168Decl *
169TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
170 NamespaceAliasDecl *Inst
171 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
172 D->getNamespaceLoc(),
173 D->getAliasLoc(),
174 D->getNamespace()->getIdentifier(),
175 D->getQualifierRange(),
176 D->getQualifier(),
177 D->getTargetNameLoc(),
178 D->getNamespace());
179 Owner->addDecl(Inst);
180 return Inst;
181}
182
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000183Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
184 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000185 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000186 if (DI->getType()->isDependentType()) {
187 DI = SemaRef.SubstType(DI, TemplateArgs,
188 D->getLocation(), D->getDeclName());
189 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000190 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000191 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000192 }
193 }
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000195 // Create the new typedef
196 TypedefDecl *Typedef
197 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000198 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199 if (Invalid)
200 Typedef->setInvalidDecl();
201
John McCall5126fd02009-12-30 00:31:22 +0000202 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000203 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
204 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000205 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
206 }
207
John McCall46460a62010-01-20 21:53:11 +0000208 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000209 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000211 return Typedef;
212}
213
Douglas Gregor6eef5192009-12-14 19:27:10 +0000214/// \brief Instantiate the arguments provided as part of initialization.
215///
216/// \returns true if an error occurred, false otherwise.
217static bool InstantiateInitializationArguments(Sema &SemaRef,
218 Expr **Args, unsigned NumArgs,
219 const MultiLevelTemplateArgumentList &TemplateArgs,
220 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
221 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
222 for (unsigned I = 0; I != NumArgs; ++I) {
223 // When we hit the first defaulted argument, break out of the loop:
224 // we don't pass those default arguments on.
225 if (Args[I]->isDefaultArgument())
226 break;
227
228 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
229 if (Arg.isInvalid())
230 return true;
231
232 Expr *ArgExpr = (Expr *)Arg.get();
233 InitArgs.push_back(Arg.release());
234
235 // FIXME: We're faking all of the comma locations. Do we need them?
236 FakeCommaLocs.push_back(
237 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
238 }
239
240 return false;
241}
242
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000243/// \brief Instantiate an initializer, breaking it into separate
244/// initialization arguments.
245///
246/// \param S The semantic analysis object.
247///
248/// \param Init The initializer to instantiate.
249///
250/// \param TemplateArgs Template arguments to be substituted into the
251/// initializer.
252///
253/// \param NewArgs Will be filled in with the instantiation arguments.
254///
255/// \returns true if an error occurred, false otherwise
256static bool InstantiateInitializer(Sema &S, Expr *Init,
257 const MultiLevelTemplateArgumentList &TemplateArgs,
258 SourceLocation &LParenLoc,
259 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
260 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
261 SourceLocation &RParenLoc) {
262 NewArgs.clear();
263 LParenLoc = SourceLocation();
264 RParenLoc = SourceLocation();
265
266 if (!Init)
267 return false;
268
269 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
270 Init = ExprTemp->getSubExpr();
271
272 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
273 Init = Binder->getSubExpr();
274
275 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
276 Init = ICE->getSubExprAsWritten();
277
278 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
279 LParenLoc = ParenList->getLParenLoc();
280 RParenLoc = ParenList->getRParenLoc();
281 return InstantiateInitializationArguments(S, ParenList->getExprs(),
282 ParenList->getNumExprs(),
283 TemplateArgs, CommaLocs,
284 NewArgs);
285 }
286
287 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
288 if (InstantiateInitializationArguments(S,
289 Construct->getArgs(),
290 Construct->getNumArgs(),
291 TemplateArgs,
292 CommaLocs, NewArgs))
293 return true;
294
295 // FIXME: Fake locations!
296 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
297 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
298 return false;
299 }
300
301 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
302 if (Result.isInvalid())
303 return true;
304
305 NewArgs.push_back(Result.takeAs<Expr>());
306 return false;
307}
308
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000309Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000310 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000311 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000312 TemplateArgs,
313 D->getTypeSpecStartLoc(),
314 D->getDeclName());
315 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000316 return 0;
317
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000318 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000319 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
320 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000321 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000322 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000323 Var->setThreadSpecified(D->isThreadSpecified());
324 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
325 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000326
John McCallb6217662010-03-15 10:12:16 +0000327 // Substitute the nested name specifier, if any.
328 if (SubstQualifier(D, Var))
329 return 0;
330
Mike Stump1eb44332009-09-09 15:08:12 +0000331 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000332 // out-of-line, the instantiation will have the same lexical
333 // context (which will be a namespace scope) as the template.
334 if (D->isOutOfLine())
335 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000336
John McCall46460a62010-01-20 21:53:11 +0000337 Var->setAccess(D->getAccess());
338
Mike Stump390b4cc2009-05-16 07:39:55 +0000339 // FIXME: In theory, we could have a previous declaration for variables that
340 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000341 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000342 // FIXME: having to fake up a LookupResult is dumb.
343 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000344 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000345 if (D->isStaticDataMember())
346 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000347 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor7caa6822009-07-24 20:34:43 +0000349 if (D->isOutOfLine()) {
350 D->getLexicalDeclContext()->addDecl(Var);
351 Owner->makeDeclVisibleInContext(Var);
352 } else {
353 Owner->addDecl(Var);
354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000356 // Link instantiations of static data members back to the template from
357 // which they were instantiated.
358 if (Var->isStaticDataMember())
359 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000360 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000361
Douglas Gregor60c93c92010-02-09 07:26:29 +0000362 if (Var->getAnyInitializer()) {
363 // We already have an initializer in the class.
364 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000365 if (Var->isStaticDataMember() && !D->isOutOfLine())
366 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
367 else
368 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
369
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000370 // Instantiate the initializer.
371 SourceLocation LParenLoc, RParenLoc;
372 llvm::SmallVector<SourceLocation, 4> CommaLocs;
373 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
374 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
375 CommaLocs, InitArgs, RParenLoc)) {
376 // Attach the initializer to the declaration.
377 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000378 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000379 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000380 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000381 move_arg(InitArgs),
382 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000383 RParenLoc);
384 } else if (InitArgs.size() == 1) {
385 Expr *Init = (Expr*)(InitArgs.take()[0]);
386 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
387 SemaRef.Owned(Init),
388 false);
389 } else {
390 assert(InitArgs.size() == 0);
391 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000392 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000393 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000394 // FIXME: Not too happy about invalidating the declaration
395 // because of a bogus initializer.
396 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000397 }
398
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000399 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000400 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
401 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000402
403 return Var;
404}
405
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000406Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
407 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000408 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000409 if (DI->getType()->isDependentType()) {
410 DI = SemaRef.SubstType(DI, TemplateArgs,
411 D->getLocation(), D->getDeclName());
412 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000413 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000414 Invalid = true;
415 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000416 // C++ [temp.arg.type]p3:
417 // If a declaration acquires a function type through a type
418 // dependent on a template-parameter and this causes a
419 // declaration that does not use the syntactic form of a
420 // function declarator to have function type, the program is
421 // ill-formed.
422 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000423 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000424 Invalid = true;
425 }
426 }
427
428 Expr *BitWidth = D->getBitWidth();
429 if (Invalid)
430 BitWidth = 0;
431 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000432 // The bit-width expression is not potentially evaluated.
433 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000435 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000436 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000437 if (InstantiatedBitWidth.isInvalid()) {
438 Invalid = true;
439 BitWidth = 0;
440 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000441 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000442 }
443
John McCall07fb6be2009-10-22 23:33:21 +0000444 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
445 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000446 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000447 D->getLocation(),
448 D->isMutable(),
449 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000450 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000451 D->getAccess(),
452 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000453 if (!Field) {
454 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000455 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000456 }
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000458 InstantiateAttrs(D, Field);
459
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000460 if (Invalid)
461 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000463 if (!Field->getDeclName()) {
464 // Keep track of where this decl came from.
465 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000466 }
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000468 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000469 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000470 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000471
472 return Field;
473}
474
John McCall02cace72009-08-28 07:59:38 +0000475Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
476 FriendDecl::FriendUnion FU;
477
478 // Handle friend type expressions by simply substituting template
479 // parameters into the pattern type.
480 if (Type *Ty = D->getFriendType()) {
481 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
482 D->getLocation(), DeclarationName());
483 if (T.isNull()) return 0;
484
485 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
486 FU = T.getTypePtr();
487
488 // Handle everything else by appropriate substitution.
489 } else {
490 NamedDecl *ND = D->getFriendDecl();
491 assert(ND && "friend decl must be a decl or a type!");
492
Douglas Gregora735b202009-10-13 14:39:41 +0000493 // FIXME: We have a problem here, because the nested call to Visit(ND)
494 // will inject the thing that the friend references into the current
495 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000496 Decl *NewND;
497
498 // Hack to make this work almost well pending a rewrite.
Douglas Gregor63644fa2010-02-07 10:31:35 +0000499 if (ND->getDeclContext()->isRecord()) {
500 if (!ND->getDeclContext()->isDependentContext()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000501 NewND = SemaRef.FindInstantiatedDecl(D->getLocation(), ND,
502 TemplateArgs);
Douglas Gregor63644fa2010-02-07 10:31:35 +0000503 } else {
504 // FIXME: Hack to avoid crashing when incorrectly trying to instantiate
505 // templated friend declarations. This doesn't produce a correct AST;
506 // however this is sufficient for some AST analysis. The real solution
507 // must be put in place during the pending rewrite. See PR5848.
508 return 0;
509 }
510 } else if (D->wasSpecialization()) {
Douglas Gregor7557a132009-12-24 20:56:24 +0000511 // Totally egregious hack to work around PR5866
512 return 0;
513 } else
John McCalle129d442009-12-17 23:21:11 +0000514 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000515 if (!NewND) return 0;
516
517 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
John McCall02cace72009-08-28 07:59:38 +0000520 FriendDecl *FD =
521 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
522 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000523 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000524 Owner->addDecl(FD);
525 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000526}
527
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000528Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
529 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregorac7610d2009-06-22 20:57:11 +0000531 // The expression in a static assertion is not potentially evaluated.
532 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000534 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000535 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000536 if (InstantiatedAssertExpr.isInvalid())
537 return 0;
538
Douglas Gregor43d9d922009-08-08 01:41:12 +0000539 OwningExprResult Message(SemaRef, D->getMessage());
540 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000541 Decl *StaticAssert
542 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000543 move(InstantiatedAssertExpr),
544 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000545 return StaticAssert;
546}
547
548Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000549 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000550 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000551 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000552 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000553 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000554 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000555 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000556 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000557 Enum->startDefinition();
558
Douglas Gregor96084f12010-03-01 19:00:07 +0000559 if (D->getDeclContext()->isFunctionOrMethod())
560 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
561
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000562 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000563
564 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000565 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
566 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000567 EC != ECEnd; ++EC) {
568 // The specified value for the enumerator.
569 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000570 if (Expr *UninstValue = EC->getInitExpr()) {
571 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000572 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000573 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000574
John McCallce3ff2b2009-08-25 22:02:44 +0000575 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000576 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000577
578 // Drop the initial value and continue.
579 bool isInvalid = false;
580 if (Value.isInvalid()) {
581 Value = SemaRef.Owned((Expr *)0);
582 isInvalid = true;
583 }
584
Mike Stump1eb44332009-09-09 15:08:12 +0000585 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000586 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
587 EC->getLocation(), EC->getIdentifier(),
588 move(Value));
589
590 if (isInvalid) {
591 if (EnumConst)
592 EnumConst->setInvalidDecl();
593 Enum->setInvalidDecl();
594 }
595
596 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000597 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000598 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000599 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000600 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000601
602 if (D->getDeclContext()->isFunctionOrMethod()) {
603 // If the enumeration is within a function or method, record the enum
604 // constant as a local.
605 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
606 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000607 }
608 }
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000610 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000611 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000612 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
613 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000614 &Enumerators[0], Enumerators.size(),
615 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000616
617 return Enum;
618}
619
Douglas Gregor6477b692009-03-25 15:04:13 +0000620Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
621 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
622 return 0;
623}
624
Douglas Gregored9c0f92009-10-29 00:04:11 +0000625namespace {
626 class SortDeclByLocation {
627 SourceManager &SourceMgr;
628
629 public:
630 explicit SortDeclByLocation(SourceManager &SourceMgr)
631 : SourceMgr(SourceMgr) { }
632
633 bool operator()(const Decl *X, const Decl *Y) const {
634 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
635 Y->getLocation());
636 }
637 };
638}
639
John McCalle29ba202009-08-20 01:44:21 +0000640Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000641 // Create a local instantiation scope for this class template, which
642 // will contain the instantiations of the template parameters.
643 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000644 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000645 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000646 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000647 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000648
649 CXXRecordDecl *Pattern = D->getTemplatedDecl();
650 CXXRecordDecl *RecordInst
651 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
652 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000653 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
654 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000655
John McCallb6217662010-03-15 10:12:16 +0000656 // Substitute the nested name specifier, if any.
657 if (SubstQualifier(Pattern, RecordInst))
658 return 0;
659
John McCalle29ba202009-08-20 01:44:21 +0000660 ClassTemplateDecl *Inst
661 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
662 D->getIdentifier(), InstParams, RecordInst, 0);
663 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000664 if (D->getFriendObjectKind())
665 Inst->setObjectOfFriendDecl(true);
666 else
667 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000668 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000669
670 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000671 SemaRef.Context.getInjectedClassNameType(RecordInst,
672 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
Douglas Gregorf0510d42009-10-12 23:11:44 +0000673
Douglas Gregor259571e2009-10-30 22:42:42 +0000674 // Finish handling of friends.
675 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000676 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000677 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000678
John McCall46460a62010-01-20 21:53:11 +0000679 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000680 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000681
682 // First, we sort the partial specializations by location, so
683 // that we instantiate them in the order they were declared.
684 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
685 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
686 P = D->getPartialSpecializations().begin(),
687 PEnd = D->getPartialSpecializations().end();
688 P != PEnd; ++P)
689 PartialSpecs.push_back(&*P);
690 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
691 SortDeclByLocation(SemaRef.SourceMgr));
692
693 // Instantiate all of the partial specializations of this member class
694 // template.
695 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
696 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
697
John McCalle29ba202009-08-20 01:44:21 +0000698 return Inst;
699}
700
Douglas Gregord60e1052009-08-27 16:57:43 +0000701Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000702TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
703 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000704 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
705
706 // Lookup the already-instantiated declaration in the instantiation
707 // of the class template and return that.
708 DeclContext::lookup_result Found
709 = Owner->lookup(ClassTemplate->getDeclName());
710 if (Found.first == Found.second)
711 return 0;
712
713 ClassTemplateDecl *InstClassTemplate
714 = dyn_cast<ClassTemplateDecl>(*Found.first);
715 if (!InstClassTemplate)
716 return 0;
717
718 Decl *DCanon = D->getCanonicalDecl();
719 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
720 P = InstClassTemplate->getPartialSpecializations().begin(),
721 PEnd = InstClassTemplate->getPartialSpecializations().end();
722 P != PEnd; ++P) {
723 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
724 return &*P;
725 }
726
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000727 return 0;
728}
729
730Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000731TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000732 // Create a local instantiation scope for this function template, which
733 // will contain the instantiations of the template parameters and then get
734 // merged with the local instantiation scope for the function template
735 // itself.
736 Sema::LocalInstantiationScope Scope(SemaRef);
737
Douglas Gregord60e1052009-08-27 16:57:43 +0000738 TemplateParameterList *TempParams = D->getTemplateParameters();
739 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000740 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000741 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000742
Douglas Gregora735b202009-10-13 14:39:41 +0000743 FunctionDecl *Instantiated = 0;
744 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
745 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
746 InstParams));
747 else
748 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
749 D->getTemplatedDecl(),
750 InstParams));
751
752 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000753 return 0;
754
John McCall46460a62010-01-20 21:53:11 +0000755 Instantiated->setAccess(D->getAccess());
756
Mike Stump1eb44332009-09-09 15:08:12 +0000757 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000758 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000759 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000760 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000761 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000762 assert(InstTemplate &&
763 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000764
765 // Link the instantiation back to the pattern *unless* this is a
766 // non-definition friend declaration.
767 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
768 !(InstTemplate->getFriendObjectKind() &&
769 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000770 InstTemplate->setInstantiatedFromMemberTemplate(D);
771
772 // Add non-friends into the owner.
773 if (!InstTemplate->getFriendObjectKind())
774 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000775 return InstTemplate;
776}
777
Douglas Gregord475b8d2009-03-25 21:17:03 +0000778Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
779 CXXRecordDecl *PrevDecl = 0;
780 if (D->isInjectedClassName())
781 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000782 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000783 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
784 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000785 TemplateArgs);
786 if (!Prev) return 0;
787 PrevDecl = cast<CXXRecordDecl>(Prev);
788 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000789
790 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000791 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000792 D->getLocation(), D->getIdentifier(),
793 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000794
795 // Substitute the nested name specifier, if any.
796 if (SubstQualifier(D, Record))
797 return 0;
798
Douglas Gregord475b8d2009-03-25 21:17:03 +0000799 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000800 // FIXME: Check against AS_none is an ugly hack to work around the issue that
801 // the tag decls introduced by friend class declarations don't have an access
802 // specifier. Remove once this area of the code gets sorted out.
803 if (D->getAccess() != AS_none)
804 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000805 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000806 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000807
John McCall02cace72009-08-28 07:59:38 +0000808 // If the original function was part of a friend declaration,
809 // inherit its namespace state.
810 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
811 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
812
Anders Carlssond8b285f2009-09-01 04:26:58 +0000813 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
814
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000815 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000816 return Record;
817}
818
John McCall02cace72009-08-28 07:59:38 +0000819/// Normal class members are of more specific types and therefore
820/// don't make it here. This function serves two purposes:
821/// 1) instantiating function templates
822/// 2) substituting friend declarations
823/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000824Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000825 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000826 // Check whether there is already a function template specialization for
827 // this declaration.
828 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
829 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000830 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000831 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000832 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000833 TemplateArgs.getInnermost().getFlatArgumentList(),
834 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000835 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
837 FunctionTemplateSpecializationInfo *Info
838 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000839 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Douglas Gregor127102b2009-06-29 20:59:39 +0000841 // If we already have a function template specialization, return it.
842 if (Info)
843 return Info->Function;
844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Douglas Gregor79c22782010-01-16 20:21:20 +0000846 bool MergeWithParentScope = (TemplateParams != 0) ||
847 !(isa<Decl>(Owner) &&
848 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
849 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregore53060f2009-06-25 22:08:12 +0000851 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000852 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
853 TInfo = SubstFunctionType(D, Params);
854 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000855 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000856 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000857
John McCall68b6b872010-02-06 01:50:47 +0000858 // If we're instantiating a local function declaration, put the result
859 // in the owner; otherwise we need to find the instantiated context.
860 DeclContext *DC;
861 if (D->getDeclContext()->isFunctionOrMethod())
862 DC = Owner;
863 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000864 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
865 TemplateArgs);
John McCall68b6b872010-02-06 01:50:47 +0000866
John McCall02cace72009-08-28 07:59:38 +0000867 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000868 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000869 D->getDeclName(), T, TInfo,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000870 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000871 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000872
873 // Substitute the nested name specifier, if any.
874 if (SubstQualifier(D, Function))
875 return 0;
876
John McCall02cace72009-08-28 07:59:38 +0000877 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Douglas Gregore53060f2009-06-25 22:08:12 +0000879 // Attach the parameters
880 for (unsigned P = 0; P < Params.size(); ++P)
881 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +0000882 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000883
Douglas Gregora735b202009-10-13 14:39:41 +0000884 if (TemplateParams) {
885 // Our resulting instantiation is actually a function template, since we
886 // are substituting only the outer template parameters. For example, given
887 //
888 // template<typename T>
889 // struct X {
890 // template<typename U> friend void f(T, U);
891 // };
892 //
893 // X<int> x;
894 //
895 // We are instantiating the friend function template "f" within X<int>,
896 // which means substituting int for T, but leaving "f" as a friend function
897 // template.
898 // Build the function template itself.
899 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
900 Function->getLocation(),
901 Function->getDeclName(),
902 TemplateParams, Function);
903 Function->setDescribedFunctionTemplate(FunctionTemplate);
904 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000905 } else if (FunctionTemplate) {
906 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +0000907 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +0000908 &TemplateArgs.getInnermost(),
909 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000910 }
Douglas Gregora735b202009-10-13 14:39:41 +0000911
Douglas Gregore53060f2009-06-25 22:08:12 +0000912 if (InitFunctionInstantiation(Function, D))
913 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Douglas Gregore53060f2009-06-25 22:08:12 +0000915 bool Redeclaration = false;
916 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000917
John McCall68263142009-11-18 22:49:29 +0000918 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
919 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
920
Douglas Gregora735b202009-10-13 14:39:41 +0000921 if (TemplateParams || !FunctionTemplate) {
922 // Look only into the namespace where the friend would be declared to
923 // find a previous declaration. This is the innermost enclosing namespace,
924 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000925 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000926
Douglas Gregora735b202009-10-13 14:39:41 +0000927 // In C++, the previous declaration we find might be a tag type
928 // (class or enum). In this case, the new declaration will hide the
929 // tag type. Note that this does does not apply if we're declaring a
930 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000931 if (Previous.isSingleTagDecl())
932 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000933 }
934
John McCall9f54ad42009-12-10 09:41:52 +0000935 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
936 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000937 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000938
Douglas Gregora735b202009-10-13 14:39:41 +0000939 // If the original function was part of a friend declaration,
940 // inherit its namespace state and add it to the owner.
941 NamedDecl *FromFriendD
942 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
943 if (FromFriendD->getFriendObjectKind()) {
944 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000945 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000946 if (TemplateParams) {
947 ToFriendD = cast<NamedDecl>(FunctionTemplate);
948 PrevDecl = FunctionTemplate->getPreviousDeclaration();
949 } else {
950 ToFriendD = Function;
951 PrevDecl = Function->getPreviousDeclaration();
952 }
953 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
954 if (!Owner->isDependentContext() && !PrevDecl)
955 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
956
957 if (!TemplateParams)
958 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
959 }
960
Douglas Gregore53060f2009-06-25 22:08:12 +0000961 return Function;
962}
963
Douglas Gregord60e1052009-08-27 16:57:43 +0000964Decl *
965TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
966 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000967 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
968 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000969 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000970 // We are creating a function template specialization from a function
971 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000972 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000973 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000974 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000975 TemplateArgs.getInnermost().getFlatArgumentList(),
976 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000977 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
979 FunctionTemplateSpecializationInfo *Info
980 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000981 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Douglas Gregor6b906862009-08-21 00:16:32 +0000983 // If we already have a function template specialization, return it.
984 if (Info)
985 return Info->Function;
986 }
987
Douglas Gregor79c22782010-01-16 20:21:20 +0000988 bool MergeWithParentScope = (TemplateParams != 0) ||
989 !(isa<Decl>(Owner) &&
990 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
991 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000992
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000993 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000994 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
995 TInfo = SubstFunctionType(D, Params);
996 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000997 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000998 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000999
1000 // Build the instantiated method declaration.
1001 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +00001002 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Douglas Gregordec06662009-08-21 18:42:58 +00001004 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001005 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001006 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1007 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1008 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001009 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1010 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001011 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001012 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001013 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001014 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1015 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1016 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1017 SemaRef.Context.getCanonicalType(ClassTy));
1018 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1019 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001020 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001021 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001022 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001023 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001024 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001025 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1026 ConvTy);
1027 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1028 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001029 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001030 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001031 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001032 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001033 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001034 D->getDeclName(), T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001035 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001036 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001037
John McCallb6217662010-03-15 10:12:16 +00001038 // Substitute the nested name specifier, if any.
1039 if (SubstQualifier(D, Method))
1040 return 0;
1041
Douglas Gregord60e1052009-08-27 16:57:43 +00001042 if (TemplateParams) {
1043 // Our resulting instantiation is actually a function template, since we
1044 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001045 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001046 // template<typename T>
1047 // struct X {
1048 // template<typename U> void f(T, U);
1049 // };
1050 //
1051 // X<int> x;
1052 //
1053 // We are instantiating the member template "f" within X<int>, which means
1054 // substituting int for T, but leaving "f" as a member function template.
1055 // Build the function template itself.
1056 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1057 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001058 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001059 TemplateParams, Method);
1060 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001061 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001062 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001063 } else if (FunctionTemplate) {
1064 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001065 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001066 &TemplateArgs.getInnermost(),
1067 InsertPos);
1068 } else {
1069 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001070 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001071 }
1072
Mike Stump1eb44332009-09-09 15:08:12 +00001073 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001074 // out-of-line, the instantiation will have the same lexical
1075 // context (which will be a namespace scope) as the template.
1076 if (D->isOutOfLine())
1077 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Douglas Gregor5545e162009-03-24 00:38:23 +00001079 // Attach the parameters
1080 for (unsigned P = 0; P < Params.size(); ++P)
1081 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001082 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001083
1084 if (InitMethodInstantiation(Method, D))
1085 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001086
John McCall68263142009-11-18 22:49:29 +00001087 LookupResult Previous(SemaRef, Name, SourceLocation(),
1088 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Douglas Gregord60e1052009-08-27 16:57:43 +00001090 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +00001091 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregordec06662009-08-21 18:42:58 +00001093 // In C++, the previous declaration we find might be a tag type
1094 // (class or enum). In this case, the new declaration will hide the
1095 // tag type. Note that this does does not apply if we're declaring a
1096 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001097 if (Previous.isSingleTagDecl())
1098 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001099 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001100
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001101 bool Redeclaration = false;
1102 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001103 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001104 /*FIXME:*/OverloadableAttrRequired);
1105
Douglas Gregor4ba31362009-12-01 17:24:26 +00001106 if (D->isPure())
1107 SemaRef.CheckPureMethod(Method, SourceRange());
1108
John McCall46460a62010-01-20 21:53:11 +00001109 Method->setAccess(D->getAccess());
1110
John McCall68263142009-11-18 22:49:29 +00001111 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +00001112 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +00001113 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001115 return Method;
1116}
1117
Douglas Gregor615c5d42009-03-24 16:43:20 +00001118Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001119 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001120}
1121
Douglas Gregor03b2b072009-03-24 00:15:49 +00001122Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001123 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001124}
1125
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001126Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001127 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001128}
1129
Douglas Gregor6477b692009-03-25 15:04:13 +00001130ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +00001131 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001132 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +00001133 if (DI) {
1134 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1135 D->getDeclName());
1136 if (DI) T = DI->getType();
1137 } else {
1138 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1139 D->getDeclName());
1140 DI = 0;
1141 }
1142
1143 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001144 return 0;
1145
John McCall58e46772009-10-23 21:48:59 +00001146 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001147
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001148 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001149 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001150 = ParmVarDecl::Create(SemaRef.Context,
1151 SemaRef.Context.getTranslationUnitDecl(),
1152 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001153 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001154
Anders Carlsson9351c172009-08-25 03:18:48 +00001155 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001156 if (D->hasUninstantiatedDefaultArg())
1157 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001158 else if (Expr *Arg = D->getDefaultArg())
1159 Param->setUninstantiatedDefaultArg(Arg);
1160
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001161 // Note: we don't try to instantiate function parameters until after
1162 // we've instantiated the function's type. Therefore, we don't have
1163 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001164 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001165 return Param;
1166}
1167
John McCalle29ba202009-08-20 01:44:21 +00001168Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1169 TemplateTypeParmDecl *D) {
1170 // TODO: don't always clone when decls are refcounted.
1171 const Type* T = D->getTypeForDecl();
1172 assert(T->isTemplateTypeParmType());
1173 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001174
John McCalle29ba202009-08-20 01:44:21 +00001175 TemplateTypeParmDecl *Inst =
1176 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001177 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001178 TTPT->getName(),
1179 D->wasDeclaredWithTypename(),
1180 D->isParameterPack());
1181
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001182 if (D->hasDefaultArgument())
1183 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001184
Douglas Gregor550d9b22009-10-31 17:21:17 +00001185 // Introduce this template parameter's instantiation into the instantiation
1186 // scope.
1187 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1188
John McCalle29ba202009-08-20 01:44:21 +00001189 return Inst;
1190}
1191
Douglas Gregor33642df2009-10-23 23:25:44 +00001192Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1193 NonTypeTemplateParmDecl *D) {
1194 // Substitute into the type of the non-type template parameter.
1195 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001196 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001197 if (DI) {
1198 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1199 D->getDeclName());
1200 if (DI) T = DI->getType();
1201 } else {
1202 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1203 D->getDeclName());
1204 DI = 0;
1205 }
1206 if (T.isNull())
1207 return 0;
1208
1209 // Check that this type is acceptable for a non-type template parameter.
1210 bool Invalid = false;
1211 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1212 if (T.isNull()) {
1213 T = SemaRef.Context.IntTy;
1214 Invalid = true;
1215 }
1216
1217 NonTypeTemplateParmDecl *Param
1218 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1219 D->getDepth() - 1, D->getPosition(),
1220 D->getIdentifier(), T, DI);
1221 if (Invalid)
1222 Param->setInvalidDecl();
1223
1224 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001225
1226 // Introduce this template parameter's instantiation into the instantiation
1227 // scope.
1228 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001229 return Param;
1230}
1231
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001232Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001233TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1234 TemplateTemplateParmDecl *D) {
1235 // Instantiate the template parameter list of the template template parameter.
1236 TemplateParameterList *TempParams = D->getTemplateParameters();
1237 TemplateParameterList *InstParams;
1238 {
1239 // Perform the actual substitution of template parameters within a new,
1240 // local instantiation scope.
1241 Sema::LocalInstantiationScope Scope(SemaRef);
1242 InstParams = SubstTemplateParams(TempParams);
1243 if (!InstParams)
1244 return NULL;
1245 }
1246
1247 // Build the template template parameter.
1248 TemplateTemplateParmDecl *Param
1249 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1250 D->getDepth() - 1, D->getPosition(),
1251 D->getIdentifier(), InstParams);
1252 Param->setDefaultArgument(D->getDefaultArgument());
1253
1254 // Introduce this template parameter's instantiation into the instantiation
1255 // scope.
1256 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1257
1258 return Param;
1259}
1260
Douglas Gregor48c32a72009-11-17 06:07:40 +00001261Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1262 // Using directives are never dependent, so they require no explicit
1263
1264 UsingDirectiveDecl *Inst
1265 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1266 D->getNamespaceKeyLocation(),
1267 D->getQualifierRange(), D->getQualifier(),
1268 D->getIdentLocation(),
1269 D->getNominatedNamespace(),
1270 D->getCommonAncestor());
1271 Owner->addDecl(Inst);
1272 return Inst;
1273}
1274
John McCalled976492009-12-04 22:46:56 +00001275Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1276 // The nested name specifier is non-dependent, so no transformation
1277 // is required.
1278
John McCall9f54ad42009-12-10 09:41:52 +00001279 // We only need to do redeclaration lookups if we're in a class
1280 // scope (in fact, it's not really even possible in non-class
1281 // scopes).
1282 bool CheckRedeclaration = Owner->isRecord();
1283
1284 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1285 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1286
John McCalled976492009-12-04 22:46:56 +00001287 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1288 D->getLocation(),
1289 D->getNestedNameRange(),
1290 D->getUsingLocation(),
1291 D->getTargetNestedNameDecl(),
1292 D->getDeclName(),
1293 D->isTypeName());
1294
1295 CXXScopeSpec SS;
1296 SS.setScopeRep(D->getTargetNestedNameDecl());
1297 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001298
1299 if (CheckRedeclaration) {
1300 Prev.setHideTags(false);
1301 SemaRef.LookupQualifiedName(Prev, Owner);
1302
1303 // Check for invalid redeclarations.
1304 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1305 D->isTypeName(), SS,
1306 D->getLocation(), Prev))
1307 NewUD->setInvalidDecl();
1308
1309 }
1310
1311 if (!NewUD->isInvalidDecl() &&
1312 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001313 D->getLocation()))
1314 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001315
John McCalled976492009-12-04 22:46:56 +00001316 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1317 NewUD->setAccess(D->getAccess());
1318 Owner->addDecl(NewUD);
1319
John McCall9f54ad42009-12-10 09:41:52 +00001320 // Don't process the shadow decls for an invalid decl.
1321 if (NewUD->isInvalidDecl())
1322 return NewUD;
1323
John McCall323c3102009-12-22 22:26:37 +00001324 bool isFunctionScope = Owner->isFunctionOrMethod();
1325
John McCall9f54ad42009-12-10 09:41:52 +00001326 // Process the shadow decls.
1327 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1328 I != E; ++I) {
1329 UsingShadowDecl *Shadow = *I;
1330 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001331 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1332 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001333 TemplateArgs));
1334
1335 if (CheckRedeclaration &&
1336 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1337 continue;
1338
1339 UsingShadowDecl *InstShadow
1340 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1341 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001342
1343 if (isFunctionScope)
1344 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001345 }
John McCalled976492009-12-04 22:46:56 +00001346
1347 return NewUD;
1348}
1349
1350Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001351 // Ignore these; we handle them in bulk when processing the UsingDecl.
1352 return 0;
John McCalled976492009-12-04 22:46:56 +00001353}
1354
John McCall7ba107a2009-11-18 02:36:19 +00001355Decl * TemplateDeclInstantiator
1356 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001357 NestedNameSpecifier *NNS =
1358 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1359 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001360 TemplateArgs);
1361 if (!NNS)
1362 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001364 CXXScopeSpec SS;
1365 SS.setRange(D->getTargetNestedNameRange());
1366 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001367
1368 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001369 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001370 D->getUsingLoc(), SS, D->getLocation(),
1371 D->getDeclName(), 0,
1372 /*instantiation*/ true,
1373 /*typename*/ true, D->getTypenameLoc());
1374 if (UD)
John McCalled976492009-12-04 22:46:56 +00001375 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1376
John McCall7ba107a2009-11-18 02:36:19 +00001377 return UD;
1378}
1379
1380Decl * TemplateDeclInstantiator
1381 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1382 NestedNameSpecifier *NNS =
1383 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1384 D->getTargetNestedNameRange(),
1385 TemplateArgs);
1386 if (!NNS)
1387 return 0;
1388
1389 CXXScopeSpec SS;
1390 SS.setRange(D->getTargetNestedNameRange());
1391 SS.setScopeRep(NNS);
1392
1393 NamedDecl *UD =
1394 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1395 D->getUsingLoc(), SS, D->getLocation(),
1396 D->getDeclName(), 0,
1397 /*instantiation*/ true,
1398 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001399 if (UD)
John McCalled976492009-12-04 22:46:56 +00001400 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1401
Anders Carlsson0d8df782009-08-29 19:37:28 +00001402 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001403}
1404
John McCallce3ff2b2009-08-25 22:02:44 +00001405Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001406 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001407 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001408 if (D->isInvalidDecl())
1409 return 0;
1410
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001411 return Instantiator.Visit(D);
1412}
1413
John McCalle29ba202009-08-20 01:44:21 +00001414/// \brief Instantiates a nested template parameter list in the current
1415/// instantiation context.
1416///
1417/// \param L The parameter list to instantiate
1418///
1419/// \returns NULL if there was an error
1420TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001421TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001422 // Get errors for all the parameters before bailing out.
1423 bool Invalid = false;
1424
1425 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001426 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001427 ParamVector Params;
1428 Params.reserve(N);
1429 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1430 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001431 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001432 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001433 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001434 }
1435
1436 // Clean up if we had an error.
1437 if (Invalid) {
1438 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1439 PI != PE; ++PI)
1440 if (*PI)
1441 (*PI)->Destroy(SemaRef.Context);
1442 return NULL;
1443 }
1444
1445 TemplateParameterList *InstL
1446 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1447 L->getLAngleLoc(), &Params.front(), N,
1448 L->getRAngleLoc());
1449 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001450}
John McCalle29ba202009-08-20 01:44:21 +00001451
Douglas Gregored9c0f92009-10-29 00:04:11 +00001452/// \brief Instantiate the declaration of a class template partial
1453/// specialization.
1454///
1455/// \param ClassTemplate the (instantiated) class template that is partially
1456// specialized by the instantiation of \p PartialSpec.
1457///
1458/// \param PartialSpec the (uninstantiated) class template partial
1459/// specialization that we are instantiating.
1460///
1461/// \returns true if there was an error, false otherwise.
1462bool
1463TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1464 ClassTemplateDecl *ClassTemplate,
1465 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001466 // Create a local instantiation scope for this class template partial
1467 // specialization, which will contain the instantiations of the template
1468 // parameters.
1469 Sema::LocalInstantiationScope Scope(SemaRef);
1470
Douglas Gregored9c0f92009-10-29 00:04:11 +00001471 // Substitute into the template parameters of the class template partial
1472 // specialization.
1473 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1474 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1475 if (!InstParams)
1476 return true;
1477
1478 // Substitute into the template arguments of the class template partial
1479 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001480 const TemplateArgumentLoc *PartialSpecTemplateArgs
1481 = PartialSpec->getTemplateArgsAsWritten();
1482 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1483
John McCalld5532b62009-11-23 01:53:49 +00001484 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001485 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001486 TemplateArgumentLoc Loc;
1487 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001488 return true;
John McCalld5532b62009-11-23 01:53:49 +00001489 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001490 }
1491
1492
1493 // Check that the template argument list is well-formed for this
1494 // class template.
1495 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1496 InstTemplateArgs.size());
1497 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1498 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001499 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001500 false,
1501 Converted))
1502 return true;
1503
1504 // Figure out where to insert this class template partial specialization
1505 // in the member template's set of class template partial specializations.
1506 llvm::FoldingSetNodeID ID;
1507 ClassTemplatePartialSpecializationDecl::Profile(ID,
1508 Converted.getFlatArguments(),
1509 Converted.flatSize(),
1510 SemaRef.Context);
1511 void *InsertPos = 0;
1512 ClassTemplateSpecializationDecl *PrevDecl
1513 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1514 InsertPos);
1515
1516 // Build the canonical type that describes the converted template
1517 // arguments of the class template partial specialization.
1518 QualType CanonType
1519 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1520 Converted.getFlatArguments(),
1521 Converted.flatSize());
1522
1523 // Build the fully-sugared type for this class template
1524 // specialization as the user wrote in the specialization
1525 // itself. This means that we'll pretty-print the type retrieved
1526 // from the specialization's declaration the way that the user
1527 // actually wrote the specialization, rather than formatting the
1528 // name based on the "canonical" representation used to store the
1529 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001530 TypeSourceInfo *WrittenTy
1531 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1532 TemplateName(ClassTemplate),
1533 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001534 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001535 CanonType);
1536
1537 if (PrevDecl) {
1538 // We've already seen a partial specialization with the same template
1539 // parameters and template arguments. This can happen, for example, when
1540 // substituting the outer template arguments ends up causing two
1541 // class template partial specializations of a member class template
1542 // to have identical forms, e.g.,
1543 //
1544 // template<typename T, typename U>
1545 // struct Outer {
1546 // template<typename X, typename Y> struct Inner;
1547 // template<typename Y> struct Inner<T, Y>;
1548 // template<typename Y> struct Inner<U, Y>;
1549 // };
1550 //
1551 // Outer<int, int> outer; // error: the partial specializations of Inner
1552 // // have the same signature.
1553 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1554 << WrittenTy;
1555 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1556 << SemaRef.Context.getTypeDeclType(PrevDecl);
1557 return true;
1558 }
1559
1560
1561 // Create the class template partial specialization declaration.
1562 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1563 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1564 PartialSpec->getLocation(),
1565 InstParams,
1566 ClassTemplate,
1567 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001568 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001569 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001570 0);
John McCallb6217662010-03-15 10:12:16 +00001571 // Substitute the nested name specifier, if any.
1572 if (SubstQualifier(PartialSpec, InstPartialSpec))
1573 return 0;
1574
Douglas Gregored9c0f92009-10-29 00:04:11 +00001575 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1576 InstPartialSpec->setTypeAsWritten(WrittenTy);
1577
1578 // Add this partial specialization to the set of class template partial
1579 // specializations.
1580 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1581 InsertPos);
1582 return false;
1583}
1584
John McCall21ef0fa2010-03-11 09:03:00 +00001585bool
1586Sema::CheckInstantiatedParams(llvm::SmallVectorImpl<ParmVarDecl*> &Params) {
1587 bool Invalid = false;
1588 for (unsigned i = 0, i_end = Params.size(); i != i_end; ++i)
1589 if (ParmVarDecl *PInst = Params[i]) {
1590 if (PInst->isInvalidDecl())
1591 Invalid = true;
1592 else if (PInst->getType()->isVoidType()) {
1593 Diag(PInst->getLocation(), diag::err_param_with_void_type);
1594 PInst->setInvalidDecl();
1595 Invalid = true;
1596 }
1597 else if (RequireNonAbstractType(PInst->getLocation(),
1598 PInst->getType(),
1599 diag::err_abstract_type_in_decl,
1600 Sema::AbstractParamType)) {
1601 PInst->setInvalidDecl();
1602 Invalid = true;
1603 }
1604 }
1605 return Invalid;
1606}
Douglas Gregor5545e162009-03-24 00:38:23 +00001607
John McCall21ef0fa2010-03-11 09:03:00 +00001608TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001609TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001610 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001611 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1612 assert(OldTInfo && "substituting function without type source info");
1613 assert(Params.empty() && "parameter vector is non-empty at start");
1614 TypeSourceInfo *NewTInfo = SemaRef.SubstType(OldTInfo, TemplateArgs,
1615 D->getTypeSpecStartLoc(),
1616 D->getDeclName());
1617 if (!NewTInfo)
1618 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001619
John McCall21ef0fa2010-03-11 09:03:00 +00001620 // Get parameters from the new type info.
1621 TypeLoc NewTL = NewTInfo->getTypeLoc();
1622 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1623 assert(NewProtoLoc && "Missing prototype?");
1624 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1625 Params.push_back(NewProtoLoc->getArg(i));
Douglas Gregor5545e162009-03-24 00:38:23 +00001626
John McCall21ef0fa2010-03-11 09:03:00 +00001627 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001628}
1629
Mike Stump1eb44332009-09-09 15:08:12 +00001630/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001631/// declaration (New) from the corresponding fields of its template (Tmpl).
1632///
1633/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001634bool
1635TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001636 FunctionDecl *Tmpl) {
1637 if (Tmpl->isDeleted())
1638 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Douglas Gregorcca9e962009-07-01 22:01:06 +00001640 // If we are performing substituting explicitly-specified template arguments
1641 // or deduced template arguments into a function template and we reach this
1642 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001643 // to keeping the new function template specialization. We therefore
1644 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001645 // into a template instantiation for this specific function template
1646 // specialization, which is not a SFINAE context, so that we diagnose any
1647 // further errors in the declaration itself.
1648 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1649 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1650 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1651 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001652 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001653 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001654 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001655 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001656 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001657 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1658 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001659 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001660 }
1661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001663 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1664 assert(Proto && "Function template without prototype?");
1665
1666 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1667 Proto->getNoReturnAttr()) {
1668 // The function has an exception specification or a "noreturn"
1669 // attribute. Substitute into each of the exception types.
1670 llvm::SmallVector<QualType, 4> Exceptions;
1671 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1672 // FIXME: Poor location information!
1673 QualType T
1674 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1675 New->getLocation(), New->getDeclName());
1676 if (T.isNull() ||
1677 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1678 continue;
1679
1680 Exceptions.push_back(T);
1681 }
1682
1683 // Rebuild the function type
1684
1685 const FunctionProtoType *NewProto
1686 = New->getType()->getAs<FunctionProtoType>();
1687 assert(NewProto && "Template instantiation without function prototype?");
1688 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1689 NewProto->arg_type_begin(),
1690 NewProto->getNumArgs(),
1691 NewProto->isVariadic(),
1692 NewProto->getTypeQuals(),
1693 Proto->hasExceptionSpec(),
1694 Proto->hasAnyExceptionSpec(),
1695 Exceptions.size(),
1696 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001697 Proto->getNoReturnAttr(),
1698 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001699 }
1700
Douglas Gregore53060f2009-06-25 22:08:12 +00001701 return false;
1702}
1703
Douglas Gregor5545e162009-03-24 00:38:23 +00001704/// \brief Initializes common fields of an instantiated method
1705/// declaration (New) from the corresponding fields of its template
1706/// (Tmpl).
1707///
1708/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001709bool
1710TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001711 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001712 if (InitFunctionInstantiation(New, Tmpl))
1713 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor5545e162009-03-24 00:38:23 +00001715 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1716 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001717 if (Tmpl->isVirtualAsWritten())
1718 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001719
1720 // FIXME: attributes
1721 // FIXME: New needs a pointer to Tmpl
1722 return false;
1723}
Douglas Gregora58861f2009-05-13 20:28:22 +00001724
1725/// \brief Instantiate the definition of the given function from its
1726/// template.
1727///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001728/// \param PointOfInstantiation the point at which the instantiation was
1729/// required. Note that this is not precisely a "point of instantiation"
1730/// for the function, but it's close.
1731///
Douglas Gregora58861f2009-05-13 20:28:22 +00001732/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001733/// function template specialization or member function of a class template
1734/// specialization.
1735///
1736/// \param Recursive if true, recursively instantiates any functions that
1737/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001738///
1739/// \param DefinitionRequired if true, then we are performing an explicit
1740/// instantiation where the body of the function is required. Complain if
1741/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001742void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001743 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001744 bool Recursive,
1745 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001746 if (Function->isInvalidDecl())
1747 return;
1748
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001749 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001751 // Never instantiate an explicit specialization.
1752 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1753 return;
1754
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001755 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001756 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001757 Stmt *Pattern = 0;
1758 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001759 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001760
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001761 if (!Pattern) {
1762 if (DefinitionRequired) {
1763 if (Function->getPrimaryTemplate())
1764 Diag(PointOfInstantiation,
1765 diag::err_explicit_instantiation_undefined_func_template)
1766 << Function->getPrimaryTemplate();
1767 else
1768 Diag(PointOfInstantiation,
1769 diag::err_explicit_instantiation_undefined_member)
1770 << 1 << Function->getDeclName() << Function->getDeclContext();
1771
1772 if (PatternDecl)
1773 Diag(PatternDecl->getLocation(),
1774 diag::note_explicit_instantiation_here);
1775 }
1776
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001777 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001778 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001779
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001780 // C++0x [temp.explicit]p9:
1781 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001782 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001783 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001784 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001785 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001786 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001787 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001789 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1790 if (Inst)
1791 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001792
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001793 // If we're performing recursive template instantiation, create our own
1794 // queue of pending implicit instantiations that we will instantiate later,
1795 // while we're still within our own instantiation context.
1796 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1797 if (Recursive)
1798 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001800 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1801
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001802 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001803 // recorded, unless we're actually a member function within a local
1804 // class, in which case we need to merge our results with the parent
1805 // scope (of the enclosing function).
1806 bool MergeWithParentScope = false;
1807 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1808 MergeWithParentScope = Rec->isLocalClass();
1809
1810 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001812 // Introduce the instantiated function parameters into the local
1813 // instantiation scope.
1814 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1815 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1816 Function->getParamDecl(I));
1817
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001818 // Enter the scope of this instantiation. We don't use
1819 // PushDeclContext because we don't have a scope.
1820 DeclContext *PreviousContext = CurContext;
1821 CurContext = Function;
1822
Mike Stump1eb44332009-09-09 15:08:12 +00001823 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001824 getTemplateInstantiationArgs(Function);
1825
1826 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001827 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001828 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1829 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1830 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001831 }
1832
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001833 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001834 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001835
Douglas Gregor52604ab2009-09-11 21:19:12 +00001836 if (Body.isInvalid())
1837 Function->setInvalidDecl();
1838
Mike Stump1eb44332009-09-09 15:08:12 +00001839 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001840 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001841
1842 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001843
1844 DeclGroupRef DG(Function);
1845 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Douglas Gregor60406be2010-01-16 22:29:39 +00001847 // This class may have local implicit instantiations that need to be
1848 // instantiation within this scope.
1849 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1850 Scope.Exit();
1851
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001852 if (Recursive) {
1853 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001854 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001855 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001857 // Restore the set of pending implicit instantiations.
1858 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1859 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001860}
1861
1862/// \brief Instantiate the definition of the given variable from its
1863/// template.
1864///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001865/// \param PointOfInstantiation the point at which the instantiation was
1866/// required. Note that this is not precisely a "point of instantiation"
1867/// for the function, but it's close.
1868///
1869/// \param Var the already-instantiated declaration of a static member
1870/// variable of a class template specialization.
1871///
1872/// \param Recursive if true, recursively instantiates any functions that
1873/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001874///
1875/// \param DefinitionRequired if true, then we are performing an explicit
1876/// instantiation where an out-of-line definition of the member variable
1877/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001878void Sema::InstantiateStaticDataMemberDefinition(
1879 SourceLocation PointOfInstantiation,
1880 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001881 bool Recursive,
1882 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001883 if (Var->isInvalidDecl())
1884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Douglas Gregor7caa6822009-07-24 20:34:43 +00001886 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001887 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001888 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001889 assert(Def->isStaticDataMember() && "Not a static data member?");
1890 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Douglas Gregor0d035142009-10-27 18:42:08 +00001892 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001893 // We did not find an out-of-line definition of this static data member,
1894 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001895 // instantiate this definition (or provide a specialization for it) in
1896 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001897 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001898 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001899 Diag(PointOfInstantiation,
1900 diag::err_explicit_instantiation_undefined_member)
1901 << 2 << Var->getDeclName() << Var->getDeclContext();
1902 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1903 }
1904
Douglas Gregor7caa6822009-07-24 20:34:43 +00001905 return;
1906 }
1907
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001908 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001909 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001910 return;
1911
1912 // C++0x [temp.explicit]p9:
1913 // Except for inline functions, other explicit instantiation declarations
1914 // have the effect of suppressing the implicit instantiation of the entity
1915 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001916 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001917 == TSK_ExplicitInstantiationDeclaration)
1918 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Douglas Gregor7caa6822009-07-24 20:34:43 +00001920 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1921 if (Inst)
1922 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Douglas Gregor7caa6822009-07-24 20:34:43 +00001924 // If we're performing recursive template instantiation, create our own
1925 // queue of pending implicit instantiations that we will instantiate later,
1926 // while we're still within our own instantiation context.
1927 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1928 if (Recursive)
1929 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Douglas Gregor7caa6822009-07-24 20:34:43 +00001931 // Enter the scope of this instantiation. We don't use
1932 // PushDeclContext because we don't have a scope.
1933 DeclContext *PreviousContext = CurContext;
1934 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001936 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001937 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001938 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001939 CurContext = PreviousContext;
1940
1941 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00001942 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1943 assert(MSInfo && "Missing member specialization information?");
1944 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1945 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001946 DeclGroupRef DG(Var);
1947 Consumer.HandleTopLevelDecl(DG);
1948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Douglas Gregor7caa6822009-07-24 20:34:43 +00001950 if (Recursive) {
1951 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001952 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001953 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Douglas Gregor7caa6822009-07-24 20:34:43 +00001955 // Restore the set of pending implicit instantiations.
1956 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001957 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001958}
Douglas Gregor815215d2009-05-27 05:35:12 +00001959
Anders Carlsson09025312009-08-29 05:16:22 +00001960void
1961Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1962 const CXXConstructorDecl *Tmpl,
1963 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Anders Carlsson09025312009-08-29 05:16:22 +00001965 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001966 bool AnyErrors = false;
1967
Anders Carlsson09025312009-08-29 05:16:22 +00001968 // Instantiate all the initializers.
1969 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001970 InitsEnd = Tmpl->init_end();
1971 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001972 CXXBaseOrMemberInitializer *Init = *Inits;
1973
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00001974 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00001975 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001976 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00001978 // Instantiate the initializer.
1979 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
1980 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
1981 AnyErrors = true;
1982 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00001983 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001984
Anders Carlsson09025312009-08-29 05:16:22 +00001985 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00001986 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001987 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001988 TemplateArgs,
1989 Init->getSourceLocation(),
1990 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001991 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001992 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00001993 New->setInvalidDecl();
1994 continue;
1995 }
1996
John McCalla93c9342009-12-07 02:54:59 +00001997 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001998 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001999 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002000 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002001 Init->getRParenLoc(),
2002 New->getParent());
2003 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002004 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002006 // Is this an anonymous union?
2007 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002008 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2009 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002010 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002011 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2012 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002013 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002014
2015 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002016 NewArgs.size(),
2017 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002018 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002019 Init->getRParenLoc());
2020 }
2021
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002022 if (NewInit.isInvalid()) {
2023 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002024 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002025 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002026 // FIXME: It would be nice if ASTOwningVector had a release function.
2027 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Anders Carlsson09025312009-08-29 05:16:22 +00002029 NewInits.push_back((MemInitTy *)NewInit.get());
2030 }
2031 }
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Anders Carlsson09025312009-08-29 05:16:22 +00002033 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002034 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002035 /*FIXME: ColonLoc */
2036 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002037 NewInits.data(), NewInits.size(),
2038 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002039}
2040
John McCall52a575a2009-08-29 08:11:13 +00002041// TODO: this could be templated if the various decl types used the
2042// same method name.
2043static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2044 ClassTemplateDecl *Instance) {
2045 Pattern = Pattern->getCanonicalDecl();
2046
2047 do {
2048 Instance = Instance->getCanonicalDecl();
2049 if (Pattern == Instance) return true;
2050 Instance = Instance->getInstantiatedFromMemberTemplate();
2051 } while (Instance);
2052
2053 return false;
2054}
2055
Douglas Gregor0d696532009-09-28 06:34:35 +00002056static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2057 FunctionTemplateDecl *Instance) {
2058 Pattern = Pattern->getCanonicalDecl();
2059
2060 do {
2061 Instance = Instance->getCanonicalDecl();
2062 if (Pattern == Instance) return true;
2063 Instance = Instance->getInstantiatedFromMemberTemplate();
2064 } while (Instance);
2065
2066 return false;
2067}
2068
Douglas Gregored9c0f92009-10-29 00:04:11 +00002069static bool
2070isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2071 ClassTemplatePartialSpecializationDecl *Instance) {
2072 Pattern
2073 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2074 do {
2075 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2076 Instance->getCanonicalDecl());
2077 if (Pattern == Instance)
2078 return true;
2079 Instance = Instance->getInstantiatedFromMember();
2080 } while (Instance);
2081
2082 return false;
2083}
2084
John McCall52a575a2009-08-29 08:11:13 +00002085static bool isInstantiationOf(CXXRecordDecl *Pattern,
2086 CXXRecordDecl *Instance) {
2087 Pattern = Pattern->getCanonicalDecl();
2088
2089 do {
2090 Instance = Instance->getCanonicalDecl();
2091 if (Pattern == Instance) return true;
2092 Instance = Instance->getInstantiatedFromMemberClass();
2093 } while (Instance);
2094
2095 return false;
2096}
2097
2098static bool isInstantiationOf(FunctionDecl *Pattern,
2099 FunctionDecl *Instance) {
2100 Pattern = Pattern->getCanonicalDecl();
2101
2102 do {
2103 Instance = Instance->getCanonicalDecl();
2104 if (Pattern == Instance) return true;
2105 Instance = Instance->getInstantiatedFromMemberFunction();
2106 } while (Instance);
2107
2108 return false;
2109}
2110
2111static bool isInstantiationOf(EnumDecl *Pattern,
2112 EnumDecl *Instance) {
2113 Pattern = Pattern->getCanonicalDecl();
2114
2115 do {
2116 Instance = Instance->getCanonicalDecl();
2117 if (Pattern == Instance) return true;
2118 Instance = Instance->getInstantiatedFromMemberEnum();
2119 } while (Instance);
2120
2121 return false;
2122}
2123
John McCalled976492009-12-04 22:46:56 +00002124static bool isInstantiationOf(UsingShadowDecl *Pattern,
2125 UsingShadowDecl *Instance,
2126 ASTContext &C) {
2127 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2128}
2129
2130static bool isInstantiationOf(UsingDecl *Pattern,
2131 UsingDecl *Instance,
2132 ASTContext &C) {
2133 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2134}
2135
John McCall7ba107a2009-11-18 02:36:19 +00002136static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2137 UsingDecl *Instance,
2138 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002139 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002140}
2141
2142static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002143 UsingDecl *Instance,
2144 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002145 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002146}
2147
John McCall52a575a2009-08-29 08:11:13 +00002148static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2149 VarDecl *Instance) {
2150 assert(Instance->isStaticDataMember());
2151
2152 Pattern = Pattern->getCanonicalDecl();
2153
2154 do {
2155 Instance = Instance->getCanonicalDecl();
2156 if (Pattern == Instance) return true;
2157 Instance = Instance->getInstantiatedFromStaticDataMember();
2158 } while (Instance);
2159
2160 return false;
2161}
2162
John McCalled976492009-12-04 22:46:56 +00002163// Other is the prospective instantiation
2164// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002165static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002166 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002167 if (UnresolvedUsingTypenameDecl *UUD
2168 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2169 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2170 return isInstantiationOf(UUD, UD, Ctx);
2171 }
2172 }
2173
2174 if (UnresolvedUsingValueDecl *UUD
2175 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002176 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2177 return isInstantiationOf(UUD, UD, Ctx);
2178 }
2179 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002180
Anders Carlsson0d8df782009-08-29 19:37:28 +00002181 return false;
2182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183
John McCall52a575a2009-08-29 08:11:13 +00002184 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2185 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002186
John McCall52a575a2009-08-29 08:11:13 +00002187 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2188 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002189
John McCall52a575a2009-08-29 08:11:13 +00002190 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2191 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002192
Douglas Gregor7caa6822009-07-24 20:34:43 +00002193 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002194 if (Var->isStaticDataMember())
2195 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2196
2197 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2198 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002199
Douglas Gregor0d696532009-09-28 06:34:35 +00002200 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2201 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2202
Douglas Gregored9c0f92009-10-29 00:04:11 +00002203 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2204 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2205 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2206 PartialSpec);
2207
Anders Carlssond8b285f2009-09-01 04:26:58 +00002208 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2209 if (!Field->getDeclName()) {
2210 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002211 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002212 cast<FieldDecl>(D);
2213 }
2214 }
Mike Stump1eb44332009-09-09 15:08:12 +00002215
John McCalled976492009-12-04 22:46:56 +00002216 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2217 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2218
2219 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2220 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2221
Douglas Gregor815215d2009-05-27 05:35:12 +00002222 return D->getDeclName() && isa<NamedDecl>(Other) &&
2223 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2224}
2225
2226template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002227static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002228 NamedDecl *D,
2229 ForwardIterator first,
2230 ForwardIterator last) {
2231 for (; first != last; ++first)
2232 if (isInstantiationOf(Ctx, D, *first))
2233 return cast<NamedDecl>(*first);
2234
2235 return 0;
2236}
2237
John McCall02cace72009-08-28 07:59:38 +00002238/// \brief Finds the instantiation of the given declaration context
2239/// within the current instantiation.
2240///
2241/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002242DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002243 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002244 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002245 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002246 return cast_or_null<DeclContext>(ID);
2247 } else return DC;
2248}
2249
Douglas Gregored961e72009-05-27 17:54:46 +00002250/// \brief Find the instantiation of the given declaration within the
2251/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002252///
2253/// This routine is intended to be used when \p D is a declaration
2254/// referenced from within a template, that needs to mapped into the
2255/// corresponding declaration within an instantiation. For example,
2256/// given:
2257///
2258/// \code
2259/// template<typename T>
2260/// struct X {
2261/// enum Kind {
2262/// KnownValue = sizeof(T)
2263/// };
2264///
2265/// bool getKind() const { return KnownValue; }
2266/// };
2267///
2268/// template struct X<int>;
2269/// \endcode
2270///
2271/// In the instantiation of X<int>::getKind(), we need to map the
2272/// EnumConstantDecl for KnownValue (which refers to
2273/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002274/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2275/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002276NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002277 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002278 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002279 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002280 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002281 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002282 // D is a local of some kind. Look into the map of local
2283 // declarations to their instantiations.
2284 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2285 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002286
Douglas Gregore95b4092009-09-16 18:34:49 +00002287 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2288 if (!Record->isDependentContext())
2289 return D;
2290
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002291 // If the RecordDecl is actually the injected-class-name or a
2292 // "templated" declaration for a class template, class template
2293 // partial specialization, or a member class of a class template,
2294 // substitute into the injected-class-name of the class template
2295 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002296 QualType T;
2297 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2298
2299 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002300 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002301 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2302 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002303 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002304
2305 // If we call SubstType with an InjectedClassNameType here we
2306 // can end up in an infinite loop.
2307 T = Context.getTypeDeclType(Record);
2308 assert(isa<InjectedClassNameType>(T) &&
2309 "type of partial specialization is not an InjectedClassNameType");
2310 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2311 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002312
2313 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002314 // Substitute into the injected-class-name to get the type
2315 // corresponding to the instantiation we want, which may also be
2316 // the current instantiation (if we're in a template
2317 // definition). This substitution should never fail, since we
2318 // know we can instantiate the injected-class-name or we
2319 // wouldn't have gotten to the injected-class-name!
2320
2321 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2322 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002323 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2324 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2325
2326 if (!T->isDependentType()) {
2327 assert(T->isRecordType() && "Instantiation must produce a record type");
2328 return T->getAs<RecordType>()->getDecl();
2329 }
2330
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002331 // We are performing "partial" template instantiation to create
2332 // the member declarations for the members of a class template
2333 // specialization. Therefore, D is actually referring to something
2334 // in the current instantiation. Look through the current
2335 // context, which contains actual instantiations, to find the
2336 // instantiation of the "current instantiation" that D refers
2337 // to.
2338 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002339 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002340 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002341 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002342 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002343 if (isInstantiationOf(ClassTemplate,
2344 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002345 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002346
2347 if (!DC->isDependentContext())
2348 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002349 }
2350
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002351 // We're performing "instantiation" of a member of the current
2352 // instantiation while we are type-checking the
2353 // definition. Compute the declaration context and return that.
2354 assert(!SawNonDependentContext &&
2355 "No dependent context while instantiating record");
2356 DeclContext *DC = computeDeclContext(T);
2357 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002358 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002359 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002360 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002361
Douglas Gregore95b4092009-09-16 18:34:49 +00002362 // Fall through to deal with other dependent record types (e.g.,
2363 // anonymous unions in class templates).
2364 }
John McCall52a575a2009-08-29 08:11:13 +00002365
Douglas Gregore95b4092009-09-16 18:34:49 +00002366 if (!ParentDC->isDependentContext())
2367 return D;
2368
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002369 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002370 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002371 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregor815215d2009-05-27 05:35:12 +00002373 if (ParentDC != D->getDeclContext()) {
2374 // We performed some kind of instantiation in the parent context,
2375 // so now we need to look into the instantiated parent context to
2376 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002377
John McCall3cb0ebd2010-03-10 03:28:59 +00002378 // If our context used to be dependent, we may need to instantiate
2379 // it before performing lookup into that context.
2380 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002381 if (!Spec->isDependentContext()) {
2382 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002383 const RecordType *Tag = T->getAs<RecordType>();
2384 assert(Tag && "type of non-dependent record is not a RecordType");
2385 if (!Tag->isBeingDefined() &&
2386 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2387 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002388 }
2389 }
2390
Douglas Gregor815215d2009-05-27 05:35:12 +00002391 NamedDecl *Result = 0;
2392 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002393 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002394 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2395 } else {
2396 // Since we don't have a name for the entity we're looking for,
2397 // our only option is to walk through all of the declarations to
2398 // find that name. This will occur in a few cases:
2399 //
2400 // - anonymous struct/union within a template
2401 // - unnamed class/struct/union/enum within a template
2402 //
2403 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002404 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002405 ParentDC->decls_begin(),
2406 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002407 }
Mike Stump1eb44332009-09-09 15:08:12 +00002408
John McCall9f54ad42009-12-10 09:41:52 +00002409 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002410 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2411 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002412 && "Unable to find instantiation of declaration!");
2413
Douglas Gregor815215d2009-05-27 05:35:12 +00002414 D = Result;
2415 }
2416
Douglas Gregor815215d2009-05-27 05:35:12 +00002417 return D;
2418}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002419
Mike Stump1eb44332009-09-09 15:08:12 +00002420/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002421/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002422void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2423 while (!PendingLocalImplicitInstantiations.empty() ||
2424 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2425 PendingImplicitInstantiation Inst;
2426
2427 if (PendingLocalImplicitInstantiations.empty()) {
2428 Inst = PendingImplicitInstantiations.front();
2429 PendingImplicitInstantiations.pop_front();
2430 } else {
2431 Inst = PendingLocalImplicitInstantiations.front();
2432 PendingLocalImplicitInstantiations.pop_front();
2433 }
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Douglas Gregor7caa6822009-07-24 20:34:43 +00002435 // Instantiate function definitions
2436 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002437 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002438 Function->getLocation(), *this,
2439 Context.getSourceManager(),
2440 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002442 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002443 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002444 continue;
2445 }
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor7caa6822009-07-24 20:34:43 +00002447 // Instantiate static data member definitions.
2448 VarDecl *Var = cast<VarDecl>(Inst.first);
2449 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002450
Chandler Carruth291b4412010-02-13 10:17:50 +00002451 // Don't try to instantiate declarations if the most recent redeclaration
2452 // is invalid.
2453 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2454 continue;
2455
2456 // Check if the most recent declaration has changed the specialization kind
2457 // and removed the need for implicit instantiation.
2458 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2459 case TSK_Undeclared:
2460 assert(false && "Cannot instantitiate an undeclared specialization.");
2461 case TSK_ExplicitInstantiationDeclaration:
2462 case TSK_ExplicitInstantiationDefinition:
2463 case TSK_ExplicitSpecialization:
2464 continue; // No longer need implicit instantiation.
2465 case TSK_ImplicitInstantiation:
2466 break;
2467 }
2468
Mike Stump1eb44332009-09-09 15:08:12 +00002469 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002470 Var->getLocation(), *this,
2471 Context.getSourceManager(),
2472 "instantiating static data member "
2473 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Douglas Gregor7caa6822009-07-24 20:34:43 +00002475 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002476 }
2477}