blob: 3a6b4cb3cc1f3dc4062441617419cfd9fb8f1015 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000020#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000022
23using namespace clang;
24
25namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000026 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000027 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028 Sema &SemaRef;
29 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000030 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Anders Carlssond8fe2d52009-11-07 06:07:58 +000032 void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
43 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000046 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000048 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitFieldDecl(FieldDecl *D);
50 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
51 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000052 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000053 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000054 Decl *VisitFunctionDecl(FunctionDecl *D,
55 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000056 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000057 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
58 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000059 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000060 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000061 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000062 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000063 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000064 Decl *VisitClassTemplatePartialSpecializationDecl(
65 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000066 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000067 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000068 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000069 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000070 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000071 Decl *VisitUsingDecl(UsingDecl *D);
72 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000073 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
74 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor8dbc2692009-03-17 21:15:40 +000076 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000077 Decl *VisitDecl(Decl *D) {
78 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
79 Diagnostic::Error,
80 "cannot instantiate %0 yet");
81 SemaRef.Diag(D->getLocation(), DiagID)
82 << D->getDeclKindName();
83
Douglas Gregor8dbc2692009-03-17 21:15:40 +000084 return 0;
85 }
Douglas Gregor5545e162009-03-24 00:38:23 +000086
John McCallfd810b12009-08-14 02:03:10 +000087 const LangOptions &getLangOptions() {
88 return SemaRef.getLangOptions();
89 }
90
Douglas Gregor5545e162009-03-24 00:38:23 +000091 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000092 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000093 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000094 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000095 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000096
97 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000098 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000099
100 bool InstantiateClassTemplatePartialSpecialization(
101 ClassTemplateDecl *ClassTemplate,
102 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000103 };
104}
105
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000106// FIXME: Is this too simple?
107void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
108 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
109 TmplAttr = TmplAttr->getNext()) {
110
111 // FIXME: Is cloning correct for all attributes?
112 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
113
114 New->addAttr(NewAttr);
115 }
116}
117
Douglas Gregor4f722be2009-03-25 15:45:12 +0000118Decl *
119TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
120 assert(false && "Translation units cannot be instantiated");
121 return D;
122}
123
124Decl *
125TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
126 assert(false && "Namespaces cannot be instantiated");
127 return D;
128}
129
John McCall3dbd3d52010-02-16 06:53:13 +0000130Decl *
131TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
132 NamespaceAliasDecl *Inst
133 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
134 D->getNamespaceLoc(),
135 D->getAliasLoc(),
136 D->getNamespace()->getIdentifier(),
137 D->getQualifierRange(),
138 D->getQualifier(),
139 D->getTargetNameLoc(),
140 D->getNamespace());
141 Owner->addDecl(Inst);
142 return Inst;
143}
144
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
146 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000147 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000148 if (DI->getType()->isDependentType()) {
149 DI = SemaRef.SubstType(DI, TemplateArgs,
150 D->getLocation(), D->getDeclName());
151 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000152 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000153 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000154 }
155 }
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000157 // Create the new typedef
158 TypedefDecl *Typedef
159 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000160 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000161 if (Invalid)
162 Typedef->setInvalidDecl();
163
John McCall5126fd02009-12-30 00:31:22 +0000164 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000165 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
166 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000167 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
168 }
169
John McCall46460a62010-01-20 21:53:11 +0000170 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000171 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000173 return Typedef;
174}
175
Douglas Gregor6eef5192009-12-14 19:27:10 +0000176/// \brief Instantiate the arguments provided as part of initialization.
177///
178/// \returns true if an error occurred, false otherwise.
179static bool InstantiateInitializationArguments(Sema &SemaRef,
180 Expr **Args, unsigned NumArgs,
181 const MultiLevelTemplateArgumentList &TemplateArgs,
182 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
183 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
184 for (unsigned I = 0; I != NumArgs; ++I) {
185 // When we hit the first defaulted argument, break out of the loop:
186 // we don't pass those default arguments on.
187 if (Args[I]->isDefaultArgument())
188 break;
189
190 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
191 if (Arg.isInvalid())
192 return true;
193
194 Expr *ArgExpr = (Expr *)Arg.get();
195 InitArgs.push_back(Arg.release());
196
197 // FIXME: We're faking all of the comma locations. Do we need them?
198 FakeCommaLocs.push_back(
199 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
200 }
201
202 return false;
203}
204
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000205/// \brief Instantiate an initializer, breaking it into separate
206/// initialization arguments.
207///
208/// \param S The semantic analysis object.
209///
210/// \param Init The initializer to instantiate.
211///
212/// \param TemplateArgs Template arguments to be substituted into the
213/// initializer.
214///
215/// \param NewArgs Will be filled in with the instantiation arguments.
216///
217/// \returns true if an error occurred, false otherwise
218static bool InstantiateInitializer(Sema &S, Expr *Init,
219 const MultiLevelTemplateArgumentList &TemplateArgs,
220 SourceLocation &LParenLoc,
221 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
222 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
223 SourceLocation &RParenLoc) {
224 NewArgs.clear();
225 LParenLoc = SourceLocation();
226 RParenLoc = SourceLocation();
227
228 if (!Init)
229 return false;
230
231 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
232 Init = ExprTemp->getSubExpr();
233
234 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
235 Init = Binder->getSubExpr();
236
237 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
238 Init = ICE->getSubExprAsWritten();
239
240 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
241 LParenLoc = ParenList->getLParenLoc();
242 RParenLoc = ParenList->getRParenLoc();
243 return InstantiateInitializationArguments(S, ParenList->getExprs(),
244 ParenList->getNumExprs(),
245 TemplateArgs, CommaLocs,
246 NewArgs);
247 }
248
249 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
250 if (InstantiateInitializationArguments(S,
251 Construct->getArgs(),
252 Construct->getNumArgs(),
253 TemplateArgs,
254 CommaLocs, NewArgs))
255 return true;
256
257 // FIXME: Fake locations!
258 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
259 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
260 return false;
261 }
262
263 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
264 if (Result.isInvalid())
265 return true;
266
267 NewArgs.push_back(Result.takeAs<Expr>());
268 return false;
269}
270
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000271Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000272 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000273 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000274 TemplateArgs,
275 D->getTypeSpecStartLoc(),
276 D->getDeclName());
277 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000278 return 0;
279
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000280 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000281 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
282 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000283 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000284 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000285 Var->setThreadSpecified(D->isThreadSpecified());
286 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
287 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000288
289 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000290 // out-of-line, the instantiation will have the same lexical
291 // context (which will be a namespace scope) as the template.
292 if (D->isOutOfLine())
293 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000294
John McCall46460a62010-01-20 21:53:11 +0000295 Var->setAccess(D->getAccess());
296
Mike Stump390b4cc2009-05-16 07:39:55 +0000297 // FIXME: In theory, we could have a previous declaration for variables that
298 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000299 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000300 // FIXME: having to fake up a LookupResult is dumb.
301 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000302 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000303 if (D->isStaticDataMember())
304 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000305 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Douglas Gregor7caa6822009-07-24 20:34:43 +0000307 if (D->isOutOfLine()) {
308 D->getLexicalDeclContext()->addDecl(Var);
309 Owner->makeDeclVisibleInContext(Var);
310 } else {
311 Owner->addDecl(Var);
312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000314 // Link instantiations of static data members back to the template from
315 // which they were instantiated.
316 if (Var->isStaticDataMember())
317 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000318 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000319
Douglas Gregor60c93c92010-02-09 07:26:29 +0000320 if (Var->getAnyInitializer()) {
321 // We already have an initializer in the class.
322 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000323 if (Var->isStaticDataMember() && !D->isOutOfLine())
324 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
325 else
326 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
327
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000328 // Instantiate the initializer.
329 SourceLocation LParenLoc, RParenLoc;
330 llvm::SmallVector<SourceLocation, 4> CommaLocs;
331 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
332 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
333 CommaLocs, InitArgs, RParenLoc)) {
334 // Attach the initializer to the declaration.
335 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000336 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000337 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000338 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000339 move_arg(InitArgs),
340 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000341 RParenLoc);
342 } else if (InitArgs.size() == 1) {
343 Expr *Init = (Expr*)(InitArgs.take()[0]);
344 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
345 SemaRef.Owned(Init),
346 false);
347 } else {
348 assert(InitArgs.size() == 0);
349 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000350 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000351 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000352 // FIXME: Not too happy about invalidating the declaration
353 // because of a bogus initializer.
354 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000355 }
356
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000357 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000358 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
359 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000360
361 return Var;
362}
363
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000364Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
365 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000366 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000367 if (DI->getType()->isDependentType()) {
368 DI = SemaRef.SubstType(DI, TemplateArgs,
369 D->getLocation(), D->getDeclName());
370 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000371 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000372 Invalid = true;
373 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000374 // C++ [temp.arg.type]p3:
375 // If a declaration acquires a function type through a type
376 // dependent on a template-parameter and this causes a
377 // declaration that does not use the syntactic form of a
378 // function declarator to have function type, the program is
379 // ill-formed.
380 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000381 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000382 Invalid = true;
383 }
384 }
385
386 Expr *BitWidth = D->getBitWidth();
387 if (Invalid)
388 BitWidth = 0;
389 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000390 // The bit-width expression is not potentially evaluated.
391 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000393 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000394 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000395 if (InstantiatedBitWidth.isInvalid()) {
396 Invalid = true;
397 BitWidth = 0;
398 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000399 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000400 }
401
John McCall07fb6be2009-10-22 23:33:21 +0000402 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
403 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000404 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000405 D->getLocation(),
406 D->isMutable(),
407 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000408 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000409 D->getAccess(),
410 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000411 if (!Field) {
412 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000413 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000414 }
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000416 InstantiateAttrs(D, Field);
417
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000418 if (Invalid)
419 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000421 if (!Field->getDeclName()) {
422 // Keep track of where this decl came from.
423 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000426 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000427 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000428 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000429
430 return Field;
431}
432
John McCall02cace72009-08-28 07:59:38 +0000433Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
434 FriendDecl::FriendUnion FU;
435
436 // Handle friend type expressions by simply substituting template
437 // parameters into the pattern type.
438 if (Type *Ty = D->getFriendType()) {
439 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
440 D->getLocation(), DeclarationName());
441 if (T.isNull()) return 0;
442
443 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
444 FU = T.getTypePtr();
445
446 // Handle everything else by appropriate substitution.
447 } else {
448 NamedDecl *ND = D->getFriendDecl();
449 assert(ND && "friend decl must be a decl or a type!");
450
Douglas Gregora735b202009-10-13 14:39:41 +0000451 // FIXME: We have a problem here, because the nested call to Visit(ND)
452 // will inject the thing that the friend references into the current
453 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000454 Decl *NewND;
455
456 // Hack to make this work almost well pending a rewrite.
Douglas Gregor63644fa2010-02-07 10:31:35 +0000457 if (ND->getDeclContext()->isRecord()) {
458 if (!ND->getDeclContext()->isDependentContext()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000459 NewND = SemaRef.FindInstantiatedDecl(D->getLocation(), ND,
460 TemplateArgs);
Douglas Gregor63644fa2010-02-07 10:31:35 +0000461 } else {
462 // FIXME: Hack to avoid crashing when incorrectly trying to instantiate
463 // templated friend declarations. This doesn't produce a correct AST;
464 // however this is sufficient for some AST analysis. The real solution
465 // must be put in place during the pending rewrite. See PR5848.
466 return 0;
467 }
468 } else if (D->wasSpecialization()) {
Douglas Gregor7557a132009-12-24 20:56:24 +0000469 // Totally egregious hack to work around PR5866
470 return 0;
471 } else
John McCalle129d442009-12-17 23:21:11 +0000472 NewND = Visit(ND);
John McCall02cace72009-08-28 07:59:38 +0000473 if (!NewND) return 0;
474
475 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
John McCall02cace72009-08-28 07:59:38 +0000478 FriendDecl *FD =
479 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
480 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000481 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000482 Owner->addDecl(FD);
483 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000484}
485
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000486Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
487 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregorac7610d2009-06-22 20:57:11 +0000489 // The expression in a static assertion is not potentially evaluated.
490 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000492 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000493 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000494 if (InstantiatedAssertExpr.isInvalid())
495 return 0;
496
Douglas Gregor43d9d922009-08-08 01:41:12 +0000497 OwningExprResult Message(SemaRef, D->getMessage());
498 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000499 Decl *StaticAssert
500 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000501 move(InstantiatedAssertExpr),
502 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000503 return StaticAssert;
504}
505
506Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000507 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000508 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000509 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000510 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000511 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000512 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000513 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000514 Enum->startDefinition();
515
Douglas Gregor96084f12010-03-01 19:00:07 +0000516 if (D->getDeclContext()->isFunctionOrMethod())
517 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
518
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000519 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000520
521 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000522 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
523 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000524 EC != ECEnd; ++EC) {
525 // The specified value for the enumerator.
526 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000527 if (Expr *UninstValue = EC->getInitExpr()) {
528 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000529 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000530 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
John McCallce3ff2b2009-08-25 22:02:44 +0000532 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000533 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000534
535 // Drop the initial value and continue.
536 bool isInvalid = false;
537 if (Value.isInvalid()) {
538 Value = SemaRef.Owned((Expr *)0);
539 isInvalid = true;
540 }
541
Mike Stump1eb44332009-09-09 15:08:12 +0000542 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000543 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
544 EC->getLocation(), EC->getIdentifier(),
545 move(Value));
546
547 if (isInvalid) {
548 if (EnumConst)
549 EnumConst->setInvalidDecl();
550 Enum->setInvalidDecl();
551 }
552
553 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000554 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000555 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000556 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000557 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000558
559 if (D->getDeclContext()->isFunctionOrMethod()) {
560 // If the enumeration is within a function or method, record the enum
561 // constant as a local.
562 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
563 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000564 }
565 }
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000567 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000568 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000569 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
570 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000571 &Enumerators[0], Enumerators.size(),
572 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000573
574 return Enum;
575}
576
Douglas Gregor6477b692009-03-25 15:04:13 +0000577Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
578 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
579 return 0;
580}
581
Douglas Gregored9c0f92009-10-29 00:04:11 +0000582namespace {
583 class SortDeclByLocation {
584 SourceManager &SourceMgr;
585
586 public:
587 explicit SortDeclByLocation(SourceManager &SourceMgr)
588 : SourceMgr(SourceMgr) { }
589
590 bool operator()(const Decl *X, const Decl *Y) const {
591 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
592 Y->getLocation());
593 }
594 };
595}
596
John McCalle29ba202009-08-20 01:44:21 +0000597Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000598 // Create a local instantiation scope for this class template, which
599 // will contain the instantiations of the template parameters.
600 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000601 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000602 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000603 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000604 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000605
606 CXXRecordDecl *Pattern = D->getTemplatedDecl();
607 CXXRecordDecl *RecordInst
608 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
609 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000610 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
611 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000612
613 ClassTemplateDecl *Inst
614 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
615 D->getIdentifier(), InstParams, RecordInst, 0);
616 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000617 if (D->getFriendObjectKind())
618 Inst->setObjectOfFriendDecl(true);
619 else
620 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000621 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000622
623 // Trigger creation of the type for the instantiation.
624 SemaRef.Context.getTypeDeclType(RecordInst);
625
Douglas Gregor259571e2009-10-30 22:42:42 +0000626 // Finish handling of friends.
627 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000628 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000629 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000630
John McCall46460a62010-01-20 21:53:11 +0000631 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000632 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000633
634 // First, we sort the partial specializations by location, so
635 // that we instantiate them in the order they were declared.
636 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
637 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
638 P = D->getPartialSpecializations().begin(),
639 PEnd = D->getPartialSpecializations().end();
640 P != PEnd; ++P)
641 PartialSpecs.push_back(&*P);
642 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
643 SortDeclByLocation(SemaRef.SourceMgr));
644
645 // Instantiate all of the partial specializations of this member class
646 // template.
647 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
648 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
649
John McCalle29ba202009-08-20 01:44:21 +0000650 return Inst;
651}
652
Douglas Gregord60e1052009-08-27 16:57:43 +0000653Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000654TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
655 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000656 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
657
658 // Lookup the already-instantiated declaration in the instantiation
659 // of the class template and return that.
660 DeclContext::lookup_result Found
661 = Owner->lookup(ClassTemplate->getDeclName());
662 if (Found.first == Found.second)
663 return 0;
664
665 ClassTemplateDecl *InstClassTemplate
666 = dyn_cast<ClassTemplateDecl>(*Found.first);
667 if (!InstClassTemplate)
668 return 0;
669
670 Decl *DCanon = D->getCanonicalDecl();
671 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
672 P = InstClassTemplate->getPartialSpecializations().begin(),
673 PEnd = InstClassTemplate->getPartialSpecializations().end();
674 P != PEnd; ++P) {
675 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
676 return &*P;
677 }
678
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000679 return 0;
680}
681
682Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000683TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000684 // Create a local instantiation scope for this function template, which
685 // will contain the instantiations of the template parameters and then get
686 // merged with the local instantiation scope for the function template
687 // itself.
688 Sema::LocalInstantiationScope Scope(SemaRef);
689
Douglas Gregord60e1052009-08-27 16:57:43 +0000690 TemplateParameterList *TempParams = D->getTemplateParameters();
691 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000692 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000693 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000694
Douglas Gregora735b202009-10-13 14:39:41 +0000695 FunctionDecl *Instantiated = 0;
696 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
697 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
698 InstParams));
699 else
700 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
701 D->getTemplatedDecl(),
702 InstParams));
703
704 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000705 return 0;
706
John McCall46460a62010-01-20 21:53:11 +0000707 Instantiated->setAccess(D->getAccess());
708
Mike Stump1eb44332009-09-09 15:08:12 +0000709 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000710 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000711 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000712 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000713 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000714 assert(InstTemplate &&
715 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000716
717 // Link the instantiation back to the pattern *unless* this is a
718 // non-definition friend declaration.
719 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
720 !(InstTemplate->getFriendObjectKind() &&
721 !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000722 InstTemplate->setInstantiatedFromMemberTemplate(D);
723
724 // Add non-friends into the owner.
725 if (!InstTemplate->getFriendObjectKind())
726 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000727 return InstTemplate;
728}
729
Douglas Gregord475b8d2009-03-25 21:17:03 +0000730Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
731 CXXRecordDecl *PrevDecl = 0;
732 if (D->isInjectedClassName())
733 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000734 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000735 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
736 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000737 TemplateArgs);
738 if (!Prev) return 0;
739 PrevDecl = cast<CXXRecordDecl>(Prev);
740 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000741
742 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000743 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000744 D->getLocation(), D->getIdentifier(),
745 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000746 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000747 // FIXME: Check against AS_none is an ugly hack to work around the issue that
748 // the tag decls introduced by friend class declarations don't have an access
749 // specifier. Remove once this area of the code gets sorted out.
750 if (D->getAccess() != AS_none)
751 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000752 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000753 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000754
John McCall02cace72009-08-28 07:59:38 +0000755 // If the original function was part of a friend declaration,
756 // inherit its namespace state.
757 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
758 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
759
Anders Carlssond8b285f2009-09-01 04:26:58 +0000760 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
761
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000762 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000763 return Record;
764}
765
John McCall02cace72009-08-28 07:59:38 +0000766/// Normal class members are of more specific types and therefore
767/// don't make it here. This function serves two purposes:
768/// 1) instantiating function templates
769/// 2) substituting friend declarations
770/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000771Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000772 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000773 // Check whether there is already a function template specialization for
774 // this declaration.
775 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
776 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000777 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000778 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000779 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000780 TemplateArgs.getInnermost().getFlatArgumentList(),
781 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000782 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000783
784 FunctionTemplateSpecializationInfo *Info
785 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000786 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Douglas Gregor127102b2009-06-29 20:59:39 +0000788 // If we already have a function template specialization, return it.
789 if (Info)
790 return Info->Function;
791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Douglas Gregor79c22782010-01-16 20:21:20 +0000793 bool MergeWithParentScope = (TemplateParams != 0) ||
794 !(isa<Decl>(Owner) &&
795 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
796 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Douglas Gregore53060f2009-06-25 22:08:12 +0000798 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000799 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000800 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000801 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000802
John McCall68b6b872010-02-06 01:50:47 +0000803 // If we're instantiating a local function declaration, put the result
804 // in the owner; otherwise we need to find the instantiated context.
805 DeclContext *DC;
806 if (D->getDeclContext()->isFunctionOrMethod())
807 DC = Owner;
808 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000809 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
810 TemplateArgs);
John McCall68b6b872010-02-06 01:50:47 +0000811
John McCall02cace72009-08-28 07:59:38 +0000812 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000813 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000814 D->getDeclName(), T, D->getTypeSourceInfo(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000815 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000816 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000817 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Douglas Gregore53060f2009-06-25 22:08:12 +0000819 // Attach the parameters
820 for (unsigned P = 0; P < Params.size(); ++P)
821 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +0000822 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000823
Douglas Gregora735b202009-10-13 14:39:41 +0000824 if (TemplateParams) {
825 // Our resulting instantiation is actually a function template, since we
826 // are substituting only the outer template parameters. For example, given
827 //
828 // template<typename T>
829 // struct X {
830 // template<typename U> friend void f(T, U);
831 // };
832 //
833 // X<int> x;
834 //
835 // We are instantiating the friend function template "f" within X<int>,
836 // which means substituting int for T, but leaving "f" as a friend function
837 // template.
838 // Build the function template itself.
839 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
840 Function->getLocation(),
841 Function->getDeclName(),
842 TemplateParams, Function);
843 Function->setDescribedFunctionTemplate(FunctionTemplate);
844 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000845 } else if (FunctionTemplate) {
846 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +0000847 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +0000848 &TemplateArgs.getInnermost(),
849 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000850 }
Douglas Gregora735b202009-10-13 14:39:41 +0000851
Douglas Gregore53060f2009-06-25 22:08:12 +0000852 if (InitFunctionInstantiation(Function, D))
853 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Douglas Gregore53060f2009-06-25 22:08:12 +0000855 bool Redeclaration = false;
856 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000857
John McCall68263142009-11-18 22:49:29 +0000858 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
859 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
860
Douglas Gregora735b202009-10-13 14:39:41 +0000861 if (TemplateParams || !FunctionTemplate) {
862 // Look only into the namespace where the friend would be declared to
863 // find a previous declaration. This is the innermost enclosing namespace,
864 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +0000865 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000866
Douglas Gregora735b202009-10-13 14:39:41 +0000867 // In C++, the previous declaration we find might be a tag type
868 // (class or enum). In this case, the new declaration will hide the
869 // tag type. Note that this does does not apply if we're declaring a
870 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +0000871 if (Previous.isSingleTagDecl())
872 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +0000873 }
874
John McCall9f54ad42009-12-10 09:41:52 +0000875 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
876 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000877 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000878
Douglas Gregora735b202009-10-13 14:39:41 +0000879 // If the original function was part of a friend declaration,
880 // inherit its namespace state and add it to the owner.
881 NamedDecl *FromFriendD
882 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
883 if (FromFriendD->getFriendObjectKind()) {
884 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +0000885 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +0000886 if (TemplateParams) {
887 ToFriendD = cast<NamedDecl>(FunctionTemplate);
888 PrevDecl = FunctionTemplate->getPreviousDeclaration();
889 } else {
890 ToFriendD = Function;
891 PrevDecl = Function->getPreviousDeclaration();
892 }
893 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
894 if (!Owner->isDependentContext() && !PrevDecl)
895 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
896
897 if (!TemplateParams)
898 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
899 }
900
Douglas Gregore53060f2009-06-25 22:08:12 +0000901 return Function;
902}
903
Douglas Gregord60e1052009-08-27 16:57:43 +0000904Decl *
905TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
906 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000907 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
908 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000909 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000910 // We are creating a function template specialization from a function
911 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000912 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000913 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000914 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000915 TemplateArgs.getInnermost().getFlatArgumentList(),
916 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000917 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000918
919 FunctionTemplateSpecializationInfo *Info
920 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000921 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregor6b906862009-08-21 00:16:32 +0000923 // If we already have a function template specialization, return it.
924 if (Info)
925 return Info->Function;
926 }
927
Douglas Gregor79c22782010-01-16 20:21:20 +0000928 bool MergeWithParentScope = (TemplateParams != 0) ||
929 !(isa<Decl>(Owner) &&
930 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
931 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000932
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000933 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000934 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000935 if (T.isNull())
936 return 0;
937
938 // Build the instantiated method declaration.
939 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000940 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Douglas Gregordec06662009-08-21 18:42:58 +0000942 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000943 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000944 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
945 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
946 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000947 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
948 Constructor->getLocation(),
949 Name, T,
John McCalla93c9342009-12-07 02:54:59 +0000950 Constructor->getTypeSourceInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000951 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000952 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000953 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
954 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
955 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
956 SemaRef.Context.getCanonicalType(ClassTy));
957 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
958 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000959 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000960 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000961 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000962 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000963 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000964 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
965 ConvTy);
966 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
967 Conversion->getLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000968 T, Conversion->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000969 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000970 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000971 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000972 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000973 D->getDeclName(), T, D->getTypeSourceInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000974 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000975 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000976
Douglas Gregord60e1052009-08-27 16:57:43 +0000977 if (TemplateParams) {
978 // Our resulting instantiation is actually a function template, since we
979 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000980 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000981 // template<typename T>
982 // struct X {
983 // template<typename U> void f(T, U);
984 // };
985 //
986 // X<int> x;
987 //
988 // We are instantiating the member template "f" within X<int>, which means
989 // substituting int for T, but leaving "f" as a member function template.
990 // Build the function template itself.
991 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
992 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000993 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000994 TemplateParams, Method);
995 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000996 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000997 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000998 } else if (FunctionTemplate) {
999 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001000 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001001 &TemplateArgs.getInnermost(),
1002 InsertPos);
1003 } else {
1004 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001005 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001006 }
1007
Mike Stump1eb44332009-09-09 15:08:12 +00001008 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001009 // out-of-line, the instantiation will have the same lexical
1010 // context (which will be a namespace scope) as the template.
1011 if (D->isOutOfLine())
1012 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Douglas Gregor5545e162009-03-24 00:38:23 +00001014 // Attach the parameters
1015 for (unsigned P = 0; P < Params.size(); ++P)
1016 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001017 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001018
1019 if (InitMethodInstantiation(Method, D))
1020 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001021
John McCall68263142009-11-18 22:49:29 +00001022 LookupResult Previous(SemaRef, Name, SourceLocation(),
1023 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Douglas Gregord60e1052009-08-27 16:57:43 +00001025 if (!FunctionTemplate || TemplateParams) {
John McCall68263142009-11-18 22:49:29 +00001026 SemaRef.LookupQualifiedName(Previous, Owner);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregordec06662009-08-21 18:42:58 +00001028 // In C++, the previous declaration we find might be a tag type
1029 // (class or enum). In this case, the new declaration will hide the
1030 // tag type. Note that this does does not apply if we're declaring a
1031 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001032 if (Previous.isSingleTagDecl())
1033 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001034 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001035
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001036 bool Redeclaration = false;
1037 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001038 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001039 /*FIXME:*/OverloadableAttrRequired);
1040
Douglas Gregor4ba31362009-12-01 17:24:26 +00001041 if (D->isPure())
1042 SemaRef.CheckPureMethod(Method, SourceRange());
1043
John McCall46460a62010-01-20 21:53:11 +00001044 Method->setAccess(D->getAccess());
1045
John McCall68263142009-11-18 22:49:29 +00001046 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
Douglas Gregora735b202009-10-13 14:39:41 +00001047 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +00001048 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001050 return Method;
1051}
1052
Douglas Gregor615c5d42009-03-24 16:43:20 +00001053Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001054 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001055}
1056
Douglas Gregor03b2b072009-03-24 00:15:49 +00001057Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001058 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001059}
1060
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001061Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001062 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001063}
1064
Douglas Gregor6477b692009-03-25 15:04:13 +00001065ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +00001066 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001067 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +00001068 if (DI) {
1069 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1070 D->getDeclName());
1071 if (DI) T = DI->getType();
1072 } else {
1073 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1074 D->getDeclName());
1075 DI = 0;
1076 }
1077
1078 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001079 return 0;
1080
John McCall58e46772009-10-23 21:48:59 +00001081 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001082
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001083 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001084 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001085 = ParmVarDecl::Create(SemaRef.Context,
1086 SemaRef.Context.getTranslationUnitDecl(),
1087 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001088 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001089
Anders Carlsson9351c172009-08-25 03:18:48 +00001090 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001091 if (D->hasUninstantiatedDefaultArg())
1092 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001093 else if (Expr *Arg = D->getDefaultArg())
1094 Param->setUninstantiatedDefaultArg(Arg);
1095
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001096 // Note: we don't try to instantiate function parameters until after
1097 // we've instantiated the function's type. Therefore, we don't have
1098 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001099 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001100 return Param;
1101}
1102
John McCalle29ba202009-08-20 01:44:21 +00001103Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1104 TemplateTypeParmDecl *D) {
1105 // TODO: don't always clone when decls are refcounted.
1106 const Type* T = D->getTypeForDecl();
1107 assert(T->isTemplateTypeParmType());
1108 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001109
John McCalle29ba202009-08-20 01:44:21 +00001110 TemplateTypeParmDecl *Inst =
1111 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001112 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001113 TTPT->getName(),
1114 D->wasDeclaredWithTypename(),
1115 D->isParameterPack());
1116
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001117 if (D->hasDefaultArgument())
1118 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001119
Douglas Gregor550d9b22009-10-31 17:21:17 +00001120 // Introduce this template parameter's instantiation into the instantiation
1121 // scope.
1122 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1123
John McCalle29ba202009-08-20 01:44:21 +00001124 return Inst;
1125}
1126
Douglas Gregor33642df2009-10-23 23:25:44 +00001127Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1128 NonTypeTemplateParmDecl *D) {
1129 // Substitute into the type of the non-type template parameter.
1130 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001131 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001132 if (DI) {
1133 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1134 D->getDeclName());
1135 if (DI) T = DI->getType();
1136 } else {
1137 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1138 D->getDeclName());
1139 DI = 0;
1140 }
1141 if (T.isNull())
1142 return 0;
1143
1144 // Check that this type is acceptable for a non-type template parameter.
1145 bool Invalid = false;
1146 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1147 if (T.isNull()) {
1148 T = SemaRef.Context.IntTy;
1149 Invalid = true;
1150 }
1151
1152 NonTypeTemplateParmDecl *Param
1153 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1154 D->getDepth() - 1, D->getPosition(),
1155 D->getIdentifier(), T, DI);
1156 if (Invalid)
1157 Param->setInvalidDecl();
1158
1159 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001160
1161 // Introduce this template parameter's instantiation into the instantiation
1162 // scope.
1163 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001164 return Param;
1165}
1166
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001167Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001168TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1169 TemplateTemplateParmDecl *D) {
1170 // Instantiate the template parameter list of the template template parameter.
1171 TemplateParameterList *TempParams = D->getTemplateParameters();
1172 TemplateParameterList *InstParams;
1173 {
1174 // Perform the actual substitution of template parameters within a new,
1175 // local instantiation scope.
1176 Sema::LocalInstantiationScope Scope(SemaRef);
1177 InstParams = SubstTemplateParams(TempParams);
1178 if (!InstParams)
1179 return NULL;
1180 }
1181
1182 // Build the template template parameter.
1183 TemplateTemplateParmDecl *Param
1184 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1185 D->getDepth() - 1, D->getPosition(),
1186 D->getIdentifier(), InstParams);
1187 Param->setDefaultArgument(D->getDefaultArgument());
1188
1189 // Introduce this template parameter's instantiation into the instantiation
1190 // scope.
1191 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1192
1193 return Param;
1194}
1195
Douglas Gregor48c32a72009-11-17 06:07:40 +00001196Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1197 // Using directives are never dependent, so they require no explicit
1198
1199 UsingDirectiveDecl *Inst
1200 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1201 D->getNamespaceKeyLocation(),
1202 D->getQualifierRange(), D->getQualifier(),
1203 D->getIdentLocation(),
1204 D->getNominatedNamespace(),
1205 D->getCommonAncestor());
1206 Owner->addDecl(Inst);
1207 return Inst;
1208}
1209
John McCalled976492009-12-04 22:46:56 +00001210Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1211 // The nested name specifier is non-dependent, so no transformation
1212 // is required.
1213
John McCall9f54ad42009-12-10 09:41:52 +00001214 // We only need to do redeclaration lookups if we're in a class
1215 // scope (in fact, it's not really even possible in non-class
1216 // scopes).
1217 bool CheckRedeclaration = Owner->isRecord();
1218
1219 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1220 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1221
John McCalled976492009-12-04 22:46:56 +00001222 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1223 D->getLocation(),
1224 D->getNestedNameRange(),
1225 D->getUsingLocation(),
1226 D->getTargetNestedNameDecl(),
1227 D->getDeclName(),
1228 D->isTypeName());
1229
1230 CXXScopeSpec SS;
1231 SS.setScopeRep(D->getTargetNestedNameDecl());
1232 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001233
1234 if (CheckRedeclaration) {
1235 Prev.setHideTags(false);
1236 SemaRef.LookupQualifiedName(Prev, Owner);
1237
1238 // Check for invalid redeclarations.
1239 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1240 D->isTypeName(), SS,
1241 D->getLocation(), Prev))
1242 NewUD->setInvalidDecl();
1243
1244 }
1245
1246 if (!NewUD->isInvalidDecl() &&
1247 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001248 D->getLocation()))
1249 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001250
John McCalled976492009-12-04 22:46:56 +00001251 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1252 NewUD->setAccess(D->getAccess());
1253 Owner->addDecl(NewUD);
1254
John McCall9f54ad42009-12-10 09:41:52 +00001255 // Don't process the shadow decls for an invalid decl.
1256 if (NewUD->isInvalidDecl())
1257 return NewUD;
1258
John McCall323c3102009-12-22 22:26:37 +00001259 bool isFunctionScope = Owner->isFunctionOrMethod();
1260
John McCall9f54ad42009-12-10 09:41:52 +00001261 // Process the shadow decls.
1262 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1263 I != E; ++I) {
1264 UsingShadowDecl *Shadow = *I;
1265 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001266 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1267 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001268 TemplateArgs));
1269
1270 if (CheckRedeclaration &&
1271 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1272 continue;
1273
1274 UsingShadowDecl *InstShadow
1275 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1276 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001277
1278 if (isFunctionScope)
1279 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001280 }
John McCalled976492009-12-04 22:46:56 +00001281
1282 return NewUD;
1283}
1284
1285Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001286 // Ignore these; we handle them in bulk when processing the UsingDecl.
1287 return 0;
John McCalled976492009-12-04 22:46:56 +00001288}
1289
John McCall7ba107a2009-11-18 02:36:19 +00001290Decl * TemplateDeclInstantiator
1291 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001292 NestedNameSpecifier *NNS =
1293 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1294 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001295 TemplateArgs);
1296 if (!NNS)
1297 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001299 CXXScopeSpec SS;
1300 SS.setRange(D->getTargetNestedNameRange());
1301 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001302
1303 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001304 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001305 D->getUsingLoc(), SS, D->getLocation(),
1306 D->getDeclName(), 0,
1307 /*instantiation*/ true,
1308 /*typename*/ true, D->getTypenameLoc());
1309 if (UD)
John McCalled976492009-12-04 22:46:56 +00001310 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1311
John McCall7ba107a2009-11-18 02:36:19 +00001312 return UD;
1313}
1314
1315Decl * TemplateDeclInstantiator
1316 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1317 NestedNameSpecifier *NNS =
1318 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1319 D->getTargetNestedNameRange(),
1320 TemplateArgs);
1321 if (!NNS)
1322 return 0;
1323
1324 CXXScopeSpec SS;
1325 SS.setRange(D->getTargetNestedNameRange());
1326 SS.setScopeRep(NNS);
1327
1328 NamedDecl *UD =
1329 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1330 D->getUsingLoc(), SS, D->getLocation(),
1331 D->getDeclName(), 0,
1332 /*instantiation*/ true,
1333 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001334 if (UD)
John McCalled976492009-12-04 22:46:56 +00001335 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1336
Anders Carlsson0d8df782009-08-29 19:37:28 +00001337 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001338}
1339
John McCallce3ff2b2009-08-25 22:02:44 +00001340Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001341 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001342 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001343 if (D->isInvalidDecl())
1344 return 0;
1345
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001346 return Instantiator.Visit(D);
1347}
1348
John McCalle29ba202009-08-20 01:44:21 +00001349/// \brief Instantiates a nested template parameter list in the current
1350/// instantiation context.
1351///
1352/// \param L The parameter list to instantiate
1353///
1354/// \returns NULL if there was an error
1355TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001356TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001357 // Get errors for all the parameters before bailing out.
1358 bool Invalid = false;
1359
1360 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001361 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001362 ParamVector Params;
1363 Params.reserve(N);
1364 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1365 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001366 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001367 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001368 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001369 }
1370
1371 // Clean up if we had an error.
1372 if (Invalid) {
1373 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1374 PI != PE; ++PI)
1375 if (*PI)
1376 (*PI)->Destroy(SemaRef.Context);
1377 return NULL;
1378 }
1379
1380 TemplateParameterList *InstL
1381 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1382 L->getLAngleLoc(), &Params.front(), N,
1383 L->getRAngleLoc());
1384 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001385}
John McCalle29ba202009-08-20 01:44:21 +00001386
Douglas Gregored9c0f92009-10-29 00:04:11 +00001387/// \brief Instantiate the declaration of a class template partial
1388/// specialization.
1389///
1390/// \param ClassTemplate the (instantiated) class template that is partially
1391// specialized by the instantiation of \p PartialSpec.
1392///
1393/// \param PartialSpec the (uninstantiated) class template partial
1394/// specialization that we are instantiating.
1395///
1396/// \returns true if there was an error, false otherwise.
1397bool
1398TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1399 ClassTemplateDecl *ClassTemplate,
1400 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001401 // Create a local instantiation scope for this class template partial
1402 // specialization, which will contain the instantiations of the template
1403 // parameters.
1404 Sema::LocalInstantiationScope Scope(SemaRef);
1405
Douglas Gregored9c0f92009-10-29 00:04:11 +00001406 // Substitute into the template parameters of the class template partial
1407 // specialization.
1408 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1409 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1410 if (!InstParams)
1411 return true;
1412
1413 // Substitute into the template arguments of the class template partial
1414 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001415 const TemplateArgumentLoc *PartialSpecTemplateArgs
1416 = PartialSpec->getTemplateArgsAsWritten();
1417 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1418
John McCalld5532b62009-11-23 01:53:49 +00001419 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001420 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001421 TemplateArgumentLoc Loc;
1422 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001423 return true;
John McCalld5532b62009-11-23 01:53:49 +00001424 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001425 }
1426
1427
1428 // Check that the template argument list is well-formed for this
1429 // class template.
1430 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1431 InstTemplateArgs.size());
1432 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1433 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001434 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001435 false,
1436 Converted))
1437 return true;
1438
1439 // Figure out where to insert this class template partial specialization
1440 // in the member template's set of class template partial specializations.
1441 llvm::FoldingSetNodeID ID;
1442 ClassTemplatePartialSpecializationDecl::Profile(ID,
1443 Converted.getFlatArguments(),
1444 Converted.flatSize(),
1445 SemaRef.Context);
1446 void *InsertPos = 0;
1447 ClassTemplateSpecializationDecl *PrevDecl
1448 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1449 InsertPos);
1450
1451 // Build the canonical type that describes the converted template
1452 // arguments of the class template partial specialization.
1453 QualType CanonType
1454 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1455 Converted.getFlatArguments(),
1456 Converted.flatSize());
1457
1458 // Build the fully-sugared type for this class template
1459 // specialization as the user wrote in the specialization
1460 // itself. This means that we'll pretty-print the type retrieved
1461 // from the specialization's declaration the way that the user
1462 // actually wrote the specialization, rather than formatting the
1463 // name based on the "canonical" representation used to store the
1464 // template arguments in the specialization.
1465 QualType WrittenTy
1466 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
John McCalld5532b62009-11-23 01:53:49 +00001467 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001468 CanonType);
1469
1470 if (PrevDecl) {
1471 // We've already seen a partial specialization with the same template
1472 // parameters and template arguments. This can happen, for example, when
1473 // substituting the outer template arguments ends up causing two
1474 // class template partial specializations of a member class template
1475 // to have identical forms, e.g.,
1476 //
1477 // template<typename T, typename U>
1478 // struct Outer {
1479 // template<typename X, typename Y> struct Inner;
1480 // template<typename Y> struct Inner<T, Y>;
1481 // template<typename Y> struct Inner<U, Y>;
1482 // };
1483 //
1484 // Outer<int, int> outer; // error: the partial specializations of Inner
1485 // // have the same signature.
1486 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1487 << WrittenTy;
1488 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1489 << SemaRef.Context.getTypeDeclType(PrevDecl);
1490 return true;
1491 }
1492
1493
1494 // Create the class template partial specialization declaration.
1495 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1496 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1497 PartialSpec->getLocation(),
1498 InstParams,
1499 ClassTemplate,
1500 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001501 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001502 0);
1503 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1504 InstPartialSpec->setTypeAsWritten(WrittenTy);
1505
1506 // Add this partial specialization to the set of class template partial
1507 // specializations.
1508 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1509 InsertPos);
1510 return false;
1511}
1512
John McCallce3ff2b2009-08-25 22:02:44 +00001513/// \brief Does substitution on the type of the given function, including
1514/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001515///
John McCallce3ff2b2009-08-25 22:02:44 +00001516/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001517///
1518/// \param Params the instantiated parameter declarations
1519
John McCallce3ff2b2009-08-25 22:02:44 +00001520/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001521/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001522QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001523TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001524 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1525 bool InvalidDecl = false;
1526
John McCallce3ff2b2009-08-25 22:02:44 +00001527 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001528 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001529 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001530 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001531 PEnd = D->param_end();
1532 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001533 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001534 if (PInst->getType()->isVoidType()) {
1535 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1536 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001537 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001538 PInst->getType(),
1539 diag::err_abstract_type_in_decl,
1540 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001541 PInst->setInvalidDecl();
1542
1543 Params.push_back(PInst);
1544 ParamTys.push_back(PInst->getType());
1545
1546 if (PInst->isInvalidDecl())
1547 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001548 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001549 InvalidDecl = true;
1550 }
1551
1552 // FIXME: Deallocate dead declarations.
1553 if (InvalidDecl)
1554 return QualType();
1555
John McCall183700f2009-09-21 23:43:11 +00001556 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001557 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001558 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001559 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1560 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001561 if (ResultType.isNull())
1562 return QualType();
1563
Jay Foadbeaaccd2009-05-21 09:52:38 +00001564 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001565 Proto->isVariadic(), Proto->getTypeQuals(),
1566 D->getLocation(), D->getDeclName());
1567}
1568
Mike Stump1eb44332009-09-09 15:08:12 +00001569/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001570/// declaration (New) from the corresponding fields of its template (Tmpl).
1571///
1572/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001573bool
1574TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001575 FunctionDecl *Tmpl) {
1576 if (Tmpl->isDeleted())
1577 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Douglas Gregorcca9e962009-07-01 22:01:06 +00001579 // If we are performing substituting explicitly-specified template arguments
1580 // or deduced template arguments into a function template and we reach this
1581 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001582 // to keeping the new function template specialization. We therefore
1583 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001584 // into a template instantiation for this specific function template
1585 // specialization, which is not a SFINAE context, so that we diagnose any
1586 // further errors in the declaration itself.
1587 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1588 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1589 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1590 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001591 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001592 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001593 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001594 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001595 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001596 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1597 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001598 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001599 }
1600 }
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001602 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1603 assert(Proto && "Function template without prototype?");
1604
1605 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1606 Proto->getNoReturnAttr()) {
1607 // The function has an exception specification or a "noreturn"
1608 // attribute. Substitute into each of the exception types.
1609 llvm::SmallVector<QualType, 4> Exceptions;
1610 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1611 // FIXME: Poor location information!
1612 QualType T
1613 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1614 New->getLocation(), New->getDeclName());
1615 if (T.isNull() ||
1616 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1617 continue;
1618
1619 Exceptions.push_back(T);
1620 }
1621
1622 // Rebuild the function type
1623
1624 const FunctionProtoType *NewProto
1625 = New->getType()->getAs<FunctionProtoType>();
1626 assert(NewProto && "Template instantiation without function prototype?");
1627 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1628 NewProto->arg_type_begin(),
1629 NewProto->getNumArgs(),
1630 NewProto->isVariadic(),
1631 NewProto->getTypeQuals(),
1632 Proto->hasExceptionSpec(),
1633 Proto->hasAnyExceptionSpec(),
1634 Exceptions.size(),
1635 Exceptions.data(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001636 Proto->getNoReturnAttr(),
1637 Proto->getCallConv()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001638 }
1639
Douglas Gregore53060f2009-06-25 22:08:12 +00001640 return false;
1641}
1642
Douglas Gregor5545e162009-03-24 00:38:23 +00001643/// \brief Initializes common fields of an instantiated method
1644/// declaration (New) from the corresponding fields of its template
1645/// (Tmpl).
1646///
1647/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001648bool
1649TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001650 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001651 if (InitFunctionInstantiation(New, Tmpl))
1652 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Douglas Gregor5545e162009-03-24 00:38:23 +00001654 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1655 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001656 if (Tmpl->isVirtualAsWritten())
1657 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001658
1659 // FIXME: attributes
1660 // FIXME: New needs a pointer to Tmpl
1661 return false;
1662}
Douglas Gregora58861f2009-05-13 20:28:22 +00001663
1664/// \brief Instantiate the definition of the given function from its
1665/// template.
1666///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001667/// \param PointOfInstantiation the point at which the instantiation was
1668/// required. Note that this is not precisely a "point of instantiation"
1669/// for the function, but it's close.
1670///
Douglas Gregora58861f2009-05-13 20:28:22 +00001671/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001672/// function template specialization or member function of a class template
1673/// specialization.
1674///
1675/// \param Recursive if true, recursively instantiates any functions that
1676/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001677///
1678/// \param DefinitionRequired if true, then we are performing an explicit
1679/// instantiation where the body of the function is required. Complain if
1680/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001681void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001682 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001683 bool Recursive,
1684 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001685 if (Function->isInvalidDecl())
1686 return;
1687
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001688 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001690 // Never instantiate an explicit specialization.
1691 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1692 return;
1693
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001694 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001695 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001696 Stmt *Pattern = 0;
1697 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001698 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001699
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001700 if (!Pattern) {
1701 if (DefinitionRequired) {
1702 if (Function->getPrimaryTemplate())
1703 Diag(PointOfInstantiation,
1704 diag::err_explicit_instantiation_undefined_func_template)
1705 << Function->getPrimaryTemplate();
1706 else
1707 Diag(PointOfInstantiation,
1708 diag::err_explicit_instantiation_undefined_member)
1709 << 1 << Function->getDeclName() << Function->getDeclContext();
1710
1711 if (PatternDecl)
1712 Diag(PatternDecl->getLocation(),
1713 diag::note_explicit_instantiation_here);
1714 }
1715
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001716 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001717 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001718
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001719 // C++0x [temp.explicit]p9:
1720 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001721 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001722 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001723 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001724 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001725 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001726 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001728 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1729 if (Inst)
1730 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001731
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001732 // If we're performing recursive template instantiation, create our own
1733 // queue of pending implicit instantiations that we will instantiate later,
1734 // while we're still within our own instantiation context.
1735 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1736 if (Recursive)
1737 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001739 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1740
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001741 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001742 // recorded, unless we're actually a member function within a local
1743 // class, in which case we need to merge our results with the parent
1744 // scope (of the enclosing function).
1745 bool MergeWithParentScope = false;
1746 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1747 MergeWithParentScope = Rec->isLocalClass();
1748
1749 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001751 // Introduce the instantiated function parameters into the local
1752 // instantiation scope.
1753 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1754 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1755 Function->getParamDecl(I));
1756
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001757 // Enter the scope of this instantiation. We don't use
1758 // PushDeclContext because we don't have a scope.
1759 DeclContext *PreviousContext = CurContext;
1760 CurContext = Function;
1761
Mike Stump1eb44332009-09-09 15:08:12 +00001762 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001763 getTemplateInstantiationArgs(Function);
1764
1765 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001766 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001767 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1768 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1769 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001770 }
1771
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001772 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001773 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001774
Douglas Gregor52604ab2009-09-11 21:19:12 +00001775 if (Body.isInvalid())
1776 Function->setInvalidDecl();
1777
Mike Stump1eb44332009-09-09 15:08:12 +00001778 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001779 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001780
1781 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001782
1783 DeclGroupRef DG(Function);
1784 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Douglas Gregor60406be2010-01-16 22:29:39 +00001786 // This class may have local implicit instantiations that need to be
1787 // instantiation within this scope.
1788 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
1789 Scope.Exit();
1790
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001791 if (Recursive) {
1792 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001793 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001794 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001796 // Restore the set of pending implicit instantiations.
1797 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1798 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001799}
1800
1801/// \brief Instantiate the definition of the given variable from its
1802/// template.
1803///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001804/// \param PointOfInstantiation the point at which the instantiation was
1805/// required. Note that this is not precisely a "point of instantiation"
1806/// for the function, but it's close.
1807///
1808/// \param Var the already-instantiated declaration of a static member
1809/// variable of a class template specialization.
1810///
1811/// \param Recursive if true, recursively instantiates any functions that
1812/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001813///
1814/// \param DefinitionRequired if true, then we are performing an explicit
1815/// instantiation where an out-of-line definition of the member variable
1816/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001817void Sema::InstantiateStaticDataMemberDefinition(
1818 SourceLocation PointOfInstantiation,
1819 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001820 bool Recursive,
1821 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001822 if (Var->isInvalidDecl())
1823 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Douglas Gregor7caa6822009-07-24 20:34:43 +00001825 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001826 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001827 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001828 assert(Def->isStaticDataMember() && "Not a static data member?");
1829 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Douglas Gregor0d035142009-10-27 18:42:08 +00001831 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001832 // We did not find an out-of-line definition of this static data member,
1833 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001834 // instantiate this definition (or provide a specialization for it) in
1835 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001836 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001837 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001838 Diag(PointOfInstantiation,
1839 diag::err_explicit_instantiation_undefined_member)
1840 << 2 << Var->getDeclName() << Var->getDeclContext();
1841 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1842 }
1843
Douglas Gregor7caa6822009-07-24 20:34:43 +00001844 return;
1845 }
1846
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001847 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001848 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001849 return;
1850
1851 // C++0x [temp.explicit]p9:
1852 // Except for inline functions, other explicit instantiation declarations
1853 // have the effect of suppressing the implicit instantiation of the entity
1854 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001855 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001856 == TSK_ExplicitInstantiationDeclaration)
1857 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Douglas Gregor7caa6822009-07-24 20:34:43 +00001859 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1860 if (Inst)
1861 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor7caa6822009-07-24 20:34:43 +00001863 // If we're performing recursive template instantiation, create our own
1864 // queue of pending implicit instantiations that we will instantiate later,
1865 // while we're still within our own instantiation context.
1866 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1867 if (Recursive)
1868 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Douglas Gregor7caa6822009-07-24 20:34:43 +00001870 // Enter the scope of this instantiation. We don't use
1871 // PushDeclContext because we don't have a scope.
1872 DeclContext *PreviousContext = CurContext;
1873 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001875 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001876 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001877 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001878 CurContext = PreviousContext;
1879
1880 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00001881 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1882 assert(MSInfo && "Missing member specialization information?");
1883 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1884 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001885 DeclGroupRef DG(Var);
1886 Consumer.HandleTopLevelDecl(DG);
1887 }
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Douglas Gregor7caa6822009-07-24 20:34:43 +00001889 if (Recursive) {
1890 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001891 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001892 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Douglas Gregor7caa6822009-07-24 20:34:43 +00001894 // Restore the set of pending implicit instantiations.
1895 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001896 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001897}
Douglas Gregor815215d2009-05-27 05:35:12 +00001898
Anders Carlsson09025312009-08-29 05:16:22 +00001899void
1900Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1901 const CXXConstructorDecl *Tmpl,
1902 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Anders Carlsson09025312009-08-29 05:16:22 +00001904 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001905 bool AnyErrors = false;
1906
Anders Carlsson09025312009-08-29 05:16:22 +00001907 // Instantiate all the initializers.
1908 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001909 InitsEnd = Tmpl->init_end();
1910 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001911 CXXBaseOrMemberInitializer *Init = *Inits;
1912
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00001913 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00001914 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001915 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00001917 // Instantiate the initializer.
1918 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
1919 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
1920 AnyErrors = true;
1921 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00001922 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001923
Anders Carlsson09025312009-08-29 05:16:22 +00001924 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00001925 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00001926 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001927 TemplateArgs,
1928 Init->getSourceLocation(),
1929 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00001930 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001931 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00001932 New->setInvalidDecl();
1933 continue;
1934 }
1935
John McCalla93c9342009-12-07 02:54:59 +00001936 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001937 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001938 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001939 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001940 Init->getRParenLoc(),
1941 New->getParent());
1942 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001943 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001945 // Is this an anonymous union?
1946 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001947 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1948 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001949 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001950 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
1951 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00001952 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001953
1954 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001955 NewArgs.size(),
1956 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001957 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00001958 Init->getRParenLoc());
1959 }
1960
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001961 if (NewInit.isInvalid()) {
1962 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00001963 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001964 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00001965 // FIXME: It would be nice if ASTOwningVector had a release function.
1966 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Anders Carlsson09025312009-08-29 05:16:22 +00001968 NewInits.push_back((MemInitTy *)NewInit.get());
1969 }
1970 }
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Anders Carlsson09025312009-08-29 05:16:22 +00001972 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001973 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001974 /*FIXME: ColonLoc */
1975 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001976 NewInits.data(), NewInits.size(),
1977 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00001978}
1979
John McCall52a575a2009-08-29 08:11:13 +00001980// TODO: this could be templated if the various decl types used the
1981// same method name.
1982static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1983 ClassTemplateDecl *Instance) {
1984 Pattern = Pattern->getCanonicalDecl();
1985
1986 do {
1987 Instance = Instance->getCanonicalDecl();
1988 if (Pattern == Instance) return true;
1989 Instance = Instance->getInstantiatedFromMemberTemplate();
1990 } while (Instance);
1991
1992 return false;
1993}
1994
Douglas Gregor0d696532009-09-28 06:34:35 +00001995static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1996 FunctionTemplateDecl *Instance) {
1997 Pattern = Pattern->getCanonicalDecl();
1998
1999 do {
2000 Instance = Instance->getCanonicalDecl();
2001 if (Pattern == Instance) return true;
2002 Instance = Instance->getInstantiatedFromMemberTemplate();
2003 } while (Instance);
2004
2005 return false;
2006}
2007
Douglas Gregored9c0f92009-10-29 00:04:11 +00002008static bool
2009isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2010 ClassTemplatePartialSpecializationDecl *Instance) {
2011 Pattern
2012 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2013 do {
2014 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2015 Instance->getCanonicalDecl());
2016 if (Pattern == Instance)
2017 return true;
2018 Instance = Instance->getInstantiatedFromMember();
2019 } while (Instance);
2020
2021 return false;
2022}
2023
John McCall52a575a2009-08-29 08:11:13 +00002024static bool isInstantiationOf(CXXRecordDecl *Pattern,
2025 CXXRecordDecl *Instance) {
2026 Pattern = Pattern->getCanonicalDecl();
2027
2028 do {
2029 Instance = Instance->getCanonicalDecl();
2030 if (Pattern == Instance) return true;
2031 Instance = Instance->getInstantiatedFromMemberClass();
2032 } while (Instance);
2033
2034 return false;
2035}
2036
2037static bool isInstantiationOf(FunctionDecl *Pattern,
2038 FunctionDecl *Instance) {
2039 Pattern = Pattern->getCanonicalDecl();
2040
2041 do {
2042 Instance = Instance->getCanonicalDecl();
2043 if (Pattern == Instance) return true;
2044 Instance = Instance->getInstantiatedFromMemberFunction();
2045 } while (Instance);
2046
2047 return false;
2048}
2049
2050static bool isInstantiationOf(EnumDecl *Pattern,
2051 EnumDecl *Instance) {
2052 Pattern = Pattern->getCanonicalDecl();
2053
2054 do {
2055 Instance = Instance->getCanonicalDecl();
2056 if (Pattern == Instance) return true;
2057 Instance = Instance->getInstantiatedFromMemberEnum();
2058 } while (Instance);
2059
2060 return false;
2061}
2062
John McCalled976492009-12-04 22:46:56 +00002063static bool isInstantiationOf(UsingShadowDecl *Pattern,
2064 UsingShadowDecl *Instance,
2065 ASTContext &C) {
2066 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2067}
2068
2069static bool isInstantiationOf(UsingDecl *Pattern,
2070 UsingDecl *Instance,
2071 ASTContext &C) {
2072 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2073}
2074
John McCall7ba107a2009-11-18 02:36:19 +00002075static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2076 UsingDecl *Instance,
2077 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002078 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002079}
2080
2081static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002082 UsingDecl *Instance,
2083 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002084 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002085}
2086
John McCall52a575a2009-08-29 08:11:13 +00002087static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2088 VarDecl *Instance) {
2089 assert(Instance->isStaticDataMember());
2090
2091 Pattern = Pattern->getCanonicalDecl();
2092
2093 do {
2094 Instance = Instance->getCanonicalDecl();
2095 if (Pattern == Instance) return true;
2096 Instance = Instance->getInstantiatedFromStaticDataMember();
2097 } while (Instance);
2098
2099 return false;
2100}
2101
John McCalled976492009-12-04 22:46:56 +00002102// Other is the prospective instantiation
2103// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002104static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002105 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002106 if (UnresolvedUsingTypenameDecl *UUD
2107 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2108 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2109 return isInstantiationOf(UUD, UD, Ctx);
2110 }
2111 }
2112
2113 if (UnresolvedUsingValueDecl *UUD
2114 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002115 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2116 return isInstantiationOf(UUD, UD, Ctx);
2117 }
2118 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002119
Anders Carlsson0d8df782009-08-29 19:37:28 +00002120 return false;
2121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
John McCall52a575a2009-08-29 08:11:13 +00002123 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2124 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002125
John McCall52a575a2009-08-29 08:11:13 +00002126 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2127 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002128
John McCall52a575a2009-08-29 08:11:13 +00002129 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2130 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002131
Douglas Gregor7caa6822009-07-24 20:34:43 +00002132 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002133 if (Var->isStaticDataMember())
2134 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2135
2136 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2137 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002138
Douglas Gregor0d696532009-09-28 06:34:35 +00002139 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2140 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2141
Douglas Gregored9c0f92009-10-29 00:04:11 +00002142 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2143 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2144 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2145 PartialSpec);
2146
Anders Carlssond8b285f2009-09-01 04:26:58 +00002147 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2148 if (!Field->getDeclName()) {
2149 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002150 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002151 cast<FieldDecl>(D);
2152 }
2153 }
Mike Stump1eb44332009-09-09 15:08:12 +00002154
John McCalled976492009-12-04 22:46:56 +00002155 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2156 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2157
2158 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2159 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2160
Douglas Gregor815215d2009-05-27 05:35:12 +00002161 return D->getDeclName() && isa<NamedDecl>(Other) &&
2162 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2163}
2164
2165template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002166static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002167 NamedDecl *D,
2168 ForwardIterator first,
2169 ForwardIterator last) {
2170 for (; first != last; ++first)
2171 if (isInstantiationOf(Ctx, D, *first))
2172 return cast<NamedDecl>(*first);
2173
2174 return 0;
2175}
2176
John McCall02cace72009-08-28 07:59:38 +00002177/// \brief Finds the instantiation of the given declaration context
2178/// within the current instantiation.
2179///
2180/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002181DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002182 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002183 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002184 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002185 return cast_or_null<DeclContext>(ID);
2186 } else return DC;
2187}
2188
Douglas Gregored961e72009-05-27 17:54:46 +00002189/// \brief Find the instantiation of the given declaration within the
2190/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002191///
2192/// This routine is intended to be used when \p D is a declaration
2193/// referenced from within a template, that needs to mapped into the
2194/// corresponding declaration within an instantiation. For example,
2195/// given:
2196///
2197/// \code
2198/// template<typename T>
2199/// struct X {
2200/// enum Kind {
2201/// KnownValue = sizeof(T)
2202/// };
2203///
2204/// bool getKind() const { return KnownValue; }
2205/// };
2206///
2207/// template struct X<int>;
2208/// \endcode
2209///
2210/// In the instantiation of X<int>::getKind(), we need to map the
2211/// EnumConstantDecl for KnownValue (which refers to
2212/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002213/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2214/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002215NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002216 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002217 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002218 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002219 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002220 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002221 // D is a local of some kind. Look into the map of local
2222 // declarations to their instantiations.
2223 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2224 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002225
Douglas Gregore95b4092009-09-16 18:34:49 +00002226 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2227 if (!Record->isDependentContext())
2228 return D;
2229
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002230 // If the RecordDecl is actually the injected-class-name or a
2231 // "templated" declaration for a class template, class template
2232 // partial specialization, or a member class of a class template,
2233 // substitute into the injected-class-name of the class template
2234 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002235 QualType T;
2236 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2237
2238 if (ClassTemplate) {
2239 T = ClassTemplate->getInjectedClassNameType(Context);
2240 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2241 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2242 T = Context.getTypeDeclType(Record);
2243 ClassTemplate = PartialSpec->getSpecializedTemplate();
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002244 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002245
2246 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002247 // Substitute into the injected-class-name to get the type
2248 // corresponding to the instantiation we want, which may also be
2249 // the current instantiation (if we're in a template
2250 // definition). This substitution should never fail, since we
2251 // know we can instantiate the injected-class-name or we
2252 // wouldn't have gotten to the injected-class-name!
2253
2254 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2255 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002256 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2257 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2258
2259 if (!T->isDependentType()) {
2260 assert(T->isRecordType() && "Instantiation must produce a record type");
2261 return T->getAs<RecordType>()->getDecl();
2262 }
2263
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002264 // We are performing "partial" template instantiation to create
2265 // the member declarations for the members of a class template
2266 // specialization. Therefore, D is actually referring to something
2267 // in the current instantiation. Look through the current
2268 // context, which contains actual instantiations, to find the
2269 // instantiation of the "current instantiation" that D refers
2270 // to.
2271 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002272 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002273 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002274 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002275 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002276 if (isInstantiationOf(ClassTemplate,
2277 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002278 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002279
2280 if (!DC->isDependentContext())
2281 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002282 }
2283
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002284 // We're performing "instantiation" of a member of the current
2285 // instantiation while we are type-checking the
2286 // definition. Compute the declaration context and return that.
2287 assert(!SawNonDependentContext &&
2288 "No dependent context while instantiating record");
2289 DeclContext *DC = computeDeclContext(T);
2290 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002291 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002292 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002293 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002294
Douglas Gregore95b4092009-09-16 18:34:49 +00002295 // Fall through to deal with other dependent record types (e.g.,
2296 // anonymous unions in class templates).
2297 }
John McCall52a575a2009-08-29 08:11:13 +00002298
Douglas Gregore95b4092009-09-16 18:34:49 +00002299 if (!ParentDC->isDependentContext())
2300 return D;
2301
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002302 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002303 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002304 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Douglas Gregor815215d2009-05-27 05:35:12 +00002306 if (ParentDC != D->getDeclContext()) {
2307 // We performed some kind of instantiation in the parent context,
2308 // so now we need to look into the instantiated parent context to
2309 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002310
2311 // If our context is a class template specialization, we may need
2312 // to instantiate it before performing lookup into that context.
2313 if (ClassTemplateSpecializationDecl *Spec
2314 = dyn_cast<ClassTemplateSpecializationDecl>(ParentDC)) {
2315 if (!Spec->isDependentContext()) {
2316 QualType T = Context.getTypeDeclType(Spec);
2317 if (const TagType *Tag = T->getAs<TagType>())
2318 if (!Tag->isBeingDefined() &&
2319 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2320 return 0;
2321 }
2322 }
2323
Douglas Gregor815215d2009-05-27 05:35:12 +00002324 NamedDecl *Result = 0;
2325 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002326 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002327 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2328 } else {
2329 // Since we don't have a name for the entity we're looking for,
2330 // our only option is to walk through all of the declarations to
2331 // find that name. This will occur in a few cases:
2332 //
2333 // - anonymous struct/union within a template
2334 // - unnamed class/struct/union/enum within a template
2335 //
2336 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002337 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002338 ParentDC->decls_begin(),
2339 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002340 }
Mike Stump1eb44332009-09-09 15:08:12 +00002341
John McCall9f54ad42009-12-10 09:41:52 +00002342 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002343 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2344 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002345 && "Unable to find instantiation of declaration!");
2346
Douglas Gregor815215d2009-05-27 05:35:12 +00002347 D = Result;
2348 }
2349
Douglas Gregor815215d2009-05-27 05:35:12 +00002350 return D;
2351}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002352
Mike Stump1eb44332009-09-09 15:08:12 +00002353/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002354/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002355void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2356 while (!PendingLocalImplicitInstantiations.empty() ||
2357 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2358 PendingImplicitInstantiation Inst;
2359
2360 if (PendingLocalImplicitInstantiations.empty()) {
2361 Inst = PendingImplicitInstantiations.front();
2362 PendingImplicitInstantiations.pop_front();
2363 } else {
2364 Inst = PendingLocalImplicitInstantiations.front();
2365 PendingLocalImplicitInstantiations.pop_front();
2366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregor7caa6822009-07-24 20:34:43 +00002368 // Instantiate function definitions
2369 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002370 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002371 Function->getLocation(), *this,
2372 Context.getSourceManager(),
2373 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002374
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002375 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002376 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002377 continue;
2378 }
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Douglas Gregor7caa6822009-07-24 20:34:43 +00002380 // Instantiate static data member definitions.
2381 VarDecl *Var = cast<VarDecl>(Inst.first);
2382 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002383
Chandler Carruth291b4412010-02-13 10:17:50 +00002384 // Don't try to instantiate declarations if the most recent redeclaration
2385 // is invalid.
2386 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2387 continue;
2388
2389 // Check if the most recent declaration has changed the specialization kind
2390 // and removed the need for implicit instantiation.
2391 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2392 case TSK_Undeclared:
2393 assert(false && "Cannot instantitiate an undeclared specialization.");
2394 case TSK_ExplicitInstantiationDeclaration:
2395 case TSK_ExplicitInstantiationDefinition:
2396 case TSK_ExplicitSpecialization:
2397 continue; // No longer need implicit instantiation.
2398 case TSK_ImplicitInstantiation:
2399 break;
2400 }
2401
Mike Stump1eb44332009-09-09 15:08:12 +00002402 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002403 Var->getLocation(), *this,
2404 Context.getSourceManager(),
2405 "instantiating static data member "
2406 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Douglas Gregor7caa6822009-07-24 20:34:43 +00002408 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002409 }
2410}