blob: 44bce7976c8e35d70103878a930dfaf5e517e09d [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"
John McCall0c01d182010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Anders Carlssond8fe2d52009-11-07 06:07:58 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
35
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036 public:
37 typedef Sema::OwningExprResult OwningExprResult;
38
39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000040 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000042
Mike Stump390b4cc2009-05-16 07:39:55 +000043 // FIXME: Once we get closer to completion, replace these manually-written
44 // declarations with automatically-generated ones from
45 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
47 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000050 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000051 Decl *VisitFieldDecl(FieldDecl *D);
52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
53 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000055 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000056 Decl *VisitFunctionDecl(FunctionDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
60 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000066 Decl *VisitClassTemplatePartialSpecializationDecl(
67 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000073 Decl *VisitUsingDecl(UsingDecl *D);
74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor8dbc2692009-03-17 21:15:40 +000078 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000079 Decl *VisitDecl(Decl *D) {
80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
81 Diagnostic::Error,
82 "cannot instantiate %0 yet");
83 SemaRef.Diag(D->getLocation(), DiagID)
84 << D->getDeclKindName();
85
Douglas Gregor8dbc2692009-03-17 21:15:40 +000086 return 0;
87 }
Douglas Gregor5545e162009-03-24 00:38:23 +000088
John McCallfd810b12009-08-14 02:03:10 +000089 const LangOptions &getLangOptions() {
90 return SemaRef.getLangOptions();
91 }
92
Douglas Gregor5545e162009-03-24 00:38:23 +000093 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000095 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000098
99 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000100 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000101
102 bool SubstQualifier(const DeclaratorDecl *OldDecl,
103 DeclaratorDecl *NewDecl);
104 bool SubstQualifier(const TagDecl *OldDecl,
105 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000106
107 bool InstantiateClassTemplatePartialSpecialization(
108 ClassTemplateDecl *ClassTemplate,
109 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000110 };
111}
112
John McCallb6217662010-03-15 10:12:16 +0000113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
114 DeclaratorDecl *NewDecl) {
115 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
116 if (!OldQual) return false;
117
118 SourceRange QualRange = OldDecl->getQualifierRange();
119
120 NestedNameSpecifier *NewQual
121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
122 if (!NewQual)
123 return true;
124
125 NewDecl->setQualifierInfo(NewQual, QualRange);
126 return false;
127}
128
129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
130 TagDecl *NewDecl) {
131 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
132 if (!OldQual) return false;
133
134 SourceRange QualRange = OldDecl->getQualifierRange();
135
136 NestedNameSpecifier *NewQual
137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
138 if (!NewQual)
139 return true;
140
141 NewDecl->setQualifierInfo(NewQual, QualRange);
142 return false;
143}
144
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000145// FIXME: Is this too simple?
146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
148 TmplAttr = TmplAttr->getNext()) {
149
150 // FIXME: Is cloning correct for all attributes?
151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
152
153 New->addAttr(NewAttr);
154 }
155}
156
Douglas Gregor4f722be2009-03-25 15:45:12 +0000157Decl *
158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
159 assert(false && "Translation units cannot be instantiated");
160 return D;
161}
162
163Decl *
164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
165 assert(false && "Namespaces cannot be instantiated");
166 return D;
167}
168
John McCall3dbd3d52010-02-16 06:53:13 +0000169Decl *
170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
171 NamespaceAliasDecl *Inst
172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
173 D->getNamespaceLoc(),
174 D->getAliasLoc(),
175 D->getNamespace()->getIdentifier(),
176 D->getQualifierRange(),
177 D->getQualifier(),
178 D->getTargetNameLoc(),
179 D->getNamespace());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
185 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000186 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000187 if (DI->getType()->isDependentType()) {
188 DI = SemaRef.SubstType(DI, TemplateArgs,
189 D->getLocation(), D->getDeclName());
190 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000191 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000193 }
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 // Create the new typedef
197 TypedefDecl *Typedef
198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000199 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200 if (Invalid)
201 Typedef->setInvalidDecl();
202
Douglas Gregord57a38e2010-04-23 16:25:07 +0000203 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
204 TagDecl *TD = TT->getDecl();
205
206 // If the TagDecl that the TypedefDecl points to is an anonymous decl
207 // keep track of the TypedefDecl.
208 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
209 TD->setTypedefForAnonDecl(Typedef);
210 }
211
John McCall5126fd02009-12-30 00:31:22 +0000212 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000213 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
214 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000215 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
216 }
217
Douglas Gregord57a38e2010-04-23 16:25:07 +0000218
John McCall46460a62010-01-20 21:53:11 +0000219 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000220 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000222 return Typedef;
223}
224
Douglas Gregor6eef5192009-12-14 19:27:10 +0000225/// \brief Instantiate the arguments provided as part of initialization.
226///
227/// \returns true if an error occurred, false otherwise.
228static bool InstantiateInitializationArguments(Sema &SemaRef,
229 Expr **Args, unsigned NumArgs,
230 const MultiLevelTemplateArgumentList &TemplateArgs,
231 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
232 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
233 for (unsigned I = 0; I != NumArgs; ++I) {
234 // When we hit the first defaulted argument, break out of the loop:
235 // we don't pass those default arguments on.
236 if (Args[I]->isDefaultArgument())
237 break;
238
239 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
240 if (Arg.isInvalid())
241 return true;
242
243 Expr *ArgExpr = (Expr *)Arg.get();
244 InitArgs.push_back(Arg.release());
245
246 // FIXME: We're faking all of the comma locations. Do we need them?
247 FakeCommaLocs.push_back(
248 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
249 }
250
251 return false;
252}
253
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000254/// \brief Instantiate an initializer, breaking it into separate
255/// initialization arguments.
256///
257/// \param S The semantic analysis object.
258///
259/// \param Init The initializer to instantiate.
260///
261/// \param TemplateArgs Template arguments to be substituted into the
262/// initializer.
263///
264/// \param NewArgs Will be filled in with the instantiation arguments.
265///
266/// \returns true if an error occurred, false otherwise
267static bool InstantiateInitializer(Sema &S, Expr *Init,
268 const MultiLevelTemplateArgumentList &TemplateArgs,
269 SourceLocation &LParenLoc,
270 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
271 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
272 SourceLocation &RParenLoc) {
273 NewArgs.clear();
274 LParenLoc = SourceLocation();
275 RParenLoc = SourceLocation();
276
277 if (!Init)
278 return false;
279
280 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
281 Init = ExprTemp->getSubExpr();
282
283 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
284 Init = Binder->getSubExpr();
285
286 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
287 Init = ICE->getSubExprAsWritten();
288
289 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
290 LParenLoc = ParenList->getLParenLoc();
291 RParenLoc = ParenList->getRParenLoc();
292 return InstantiateInitializationArguments(S, ParenList->getExprs(),
293 ParenList->getNumExprs(),
294 TemplateArgs, CommaLocs,
295 NewArgs);
296 }
297
298 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000299 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
300 if (InstantiateInitializationArguments(S,
301 Construct->getArgs(),
302 Construct->getNumArgs(),
303 TemplateArgs,
304 CommaLocs, NewArgs))
305 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000306
Douglas Gregor28329e52010-03-24 21:22:47 +0000307 // FIXME: Fake locations!
308 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
309 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
310 return false;
311 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000312 }
313
314 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
315 if (Result.isInvalid())
316 return true;
317
318 NewArgs.push_back(Result.takeAs<Expr>());
319 return false;
320}
321
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000323 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000324 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000325 TemplateArgs,
326 D->getTypeSpecStartLoc(),
327 D->getDeclName());
328 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000329 return 0;
330
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000331 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000332 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
333 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000334 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000335 D->getStorageClass(),
336 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000337 Var->setThreadSpecified(D->isThreadSpecified());
338 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
339 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCallb6217662010-03-15 10:12:16 +0000341 // Substitute the nested name specifier, if any.
342 if (SubstQualifier(D, Var))
343 return 0;
344
Mike Stump1eb44332009-09-09 15:08:12 +0000345 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000346 // out-of-line, the instantiation will have the same lexical
347 // context (which will be a namespace scope) as the template.
348 if (D->isOutOfLine())
349 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000350
John McCall46460a62010-01-20 21:53:11 +0000351 Var->setAccess(D->getAccess());
352
Mike Stump390b4cc2009-05-16 07:39:55 +0000353 // FIXME: In theory, we could have a previous declaration for variables that
354 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000355 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000356 // FIXME: having to fake up a LookupResult is dumb.
357 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000358 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000359 if (D->isStaticDataMember())
360 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000361 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Douglas Gregor7caa6822009-07-24 20:34:43 +0000363 if (D->isOutOfLine()) {
364 D->getLexicalDeclContext()->addDecl(Var);
365 Owner->makeDeclVisibleInContext(Var);
366 } else {
367 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000368
369 if (Owner->isFunctionOrMethod())
370 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000371 }
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000373 // Link instantiations of static data members back to the template from
374 // which they were instantiated.
375 if (Var->isStaticDataMember())
376 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000377 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000378
Douglas Gregor60c93c92010-02-09 07:26:29 +0000379 if (Var->getAnyInitializer()) {
380 // We already have an initializer in the class.
381 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000382 if (Var->isStaticDataMember() && !D->isOutOfLine())
383 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
384 else
385 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
386
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000387 // Instantiate the initializer.
388 SourceLocation LParenLoc, RParenLoc;
389 llvm::SmallVector<SourceLocation, 4> CommaLocs;
390 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
391 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
392 CommaLocs, InitArgs, RParenLoc)) {
393 // Attach the initializer to the declaration.
394 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000395 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000396 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000397 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000398 move_arg(InitArgs),
399 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000400 RParenLoc);
401 } else if (InitArgs.size() == 1) {
402 Expr *Init = (Expr*)(InitArgs.take()[0]);
403 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
404 SemaRef.Owned(Init),
405 false);
406 } else {
407 assert(InitArgs.size() == 0);
408 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000409 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000410 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000411 // FIXME: Not too happy about invalidating the declaration
412 // because of a bogus initializer.
413 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000414 }
415
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000416 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000417 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
418 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000419
420 return Var;
421}
422
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000423Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
424 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000425 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000426 if (DI->getType()->isDependentType()) {
427 DI = SemaRef.SubstType(DI, TemplateArgs,
428 D->getLocation(), D->getDeclName());
429 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000430 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000431 Invalid = true;
432 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000433 // C++ [temp.arg.type]p3:
434 // If a declaration acquires a function type through a type
435 // dependent on a template-parameter and this causes a
436 // declaration that does not use the syntactic form of a
437 // function declarator to have function type, the program is
438 // ill-formed.
439 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000440 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441 Invalid = true;
442 }
443 }
444
445 Expr *BitWidth = D->getBitWidth();
446 if (Invalid)
447 BitWidth = 0;
448 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000449 // The bit-width expression is not potentially evaluated.
450 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000452 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000453 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454 if (InstantiatedBitWidth.isInvalid()) {
455 Invalid = true;
456 BitWidth = 0;
457 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000458 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000459 }
460
John McCall07fb6be2009-10-22 23:33:21 +0000461 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
462 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000463 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000464 D->getLocation(),
465 D->isMutable(),
466 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000467 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000468 D->getAccess(),
469 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000470 if (!Field) {
471 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000472 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000475 InstantiateAttrs(D, Field);
476
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000477 if (Invalid)
478 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000480 if (!Field->getDeclName()) {
481 // Keep track of where this decl came from.
482 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000485 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000486 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000487 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000488
489 return Field;
490}
491
John McCall02cace72009-08-28 07:59:38 +0000492Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000493 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000494 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000495 if (TypeSourceInfo *Ty = D->getFriendType()) {
496 TypeSourceInfo *InstTy =
497 SemaRef.SubstType(Ty, TemplateArgs,
498 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000500 return 0;
John McCall02cace72009-08-28 07:59:38 +0000501
Douglas Gregor06245bf2010-04-07 17:57:12 +0000502 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
503 if (!FD)
504 return 0;
505
506 FD->setAccess(AS_public);
507 Owner->addDecl(FD);
508 return FD;
509 }
510
511 NamedDecl *ND = D->getFriendDecl();
512 assert(ND && "friend decl must be a decl or a type!");
513
John McCallaf2094e2010-04-08 09:05:18 +0000514 // All of the Visit implementations for the various potential friend
515 // declarations have to be carefully written to work for friend
516 // objects, with the most important detail being that the target
517 // decl should almost certainly not be placed in Owner.
518 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000519 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000520
John McCall02cace72009-08-28 07:59:38 +0000521 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000522 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
523 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000524 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000525 Owner->addDecl(FD);
526 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000527}
528
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000529Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
530 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregorac7610d2009-06-22 20:57:11 +0000532 // The expression in a static assertion is not potentially evaluated.
533 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000535 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000536 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000537 if (InstantiatedAssertExpr.isInvalid())
538 return 0;
539
Douglas Gregor43d9d922009-08-08 01:41:12 +0000540 OwningExprResult Message(SemaRef, D->getMessage());
541 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000542 Decl *StaticAssert
543 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000544 move(InstantiatedAssertExpr),
545 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000546 return StaticAssert;
547}
548
549Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000551 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000552 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000553 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000554 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000555 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000556 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000557 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000558 Enum->startDefinition();
559
Douglas Gregor96084f12010-03-01 19:00:07 +0000560 if (D->getDeclContext()->isFunctionOrMethod())
561 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
562
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000563 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000564
565 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000566 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
567 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000568 EC != ECEnd; ++EC) {
569 // The specified value for the enumerator.
570 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000571 if (Expr *UninstValue = EC->getInitExpr()) {
572 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000573 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000574 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000575
John McCallce3ff2b2009-08-25 22:02:44 +0000576 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000577 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000578
579 // Drop the initial value and continue.
580 bool isInvalid = false;
581 if (Value.isInvalid()) {
582 Value = SemaRef.Owned((Expr *)0);
583 isInvalid = true;
584 }
585
Mike Stump1eb44332009-09-09 15:08:12 +0000586 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000587 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
588 EC->getLocation(), EC->getIdentifier(),
589 move(Value));
590
591 if (isInvalid) {
592 if (EnumConst)
593 EnumConst->setInvalidDecl();
594 Enum->setInvalidDecl();
595 }
596
597 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000598 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000599 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000600 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000601 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000602
603 if (D->getDeclContext()->isFunctionOrMethod()) {
604 // If the enumeration is within a function or method, record the enum
605 // constant as a local.
606 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
607 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000608 }
609 }
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000611 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000612 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000613 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
614 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000615 &Enumerators[0], Enumerators.size(),
616 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000617
618 return Enum;
619}
620
Douglas Gregor6477b692009-03-25 15:04:13 +0000621Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
622 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
623 return 0;
624}
625
John McCalle29ba202009-08-20 01:44:21 +0000626Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000627 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
628
Douglas Gregor550d9b22009-10-31 17:21:17 +0000629 // Create a local instantiation scope for this class template, which
630 // will contain the instantiations of the template parameters.
631 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000632 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000633 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000634 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000635 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000636
637 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000638
639 // Instantiate the qualifier. We have to do this first in case
640 // we're a friend declaration, because if we are then we need to put
641 // the new declaration in the appropriate context.
642 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
643 if (Qualifier) {
644 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
645 Pattern->getQualifierRange(),
646 TemplateArgs);
647 if (!Qualifier) return 0;
648 }
649
650 CXXRecordDecl *PrevDecl = 0;
651 ClassTemplateDecl *PrevClassTemplate = 0;
652
653 // If this isn't a friend, then it's a member template, in which
654 // case we just want to build the instantiation in the
655 // specialization. If it is a friend, we want to build it in
656 // the appropriate context.
657 DeclContext *DC = Owner;
658 if (isFriend) {
659 if (Qualifier) {
660 CXXScopeSpec SS;
661 SS.setScopeRep(Qualifier);
662 SS.setRange(Pattern->getQualifierRange());
663 DC = SemaRef.computeDeclContext(SS);
664 if (!DC) return 0;
665 } else {
666 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
667 Pattern->getDeclContext(),
668 TemplateArgs);
669 }
670
671 // Look for a previous declaration of the template in the owning
672 // context.
673 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
674 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
675 SemaRef.LookupQualifiedName(R, DC);
676
677 if (R.isSingleResult()) {
678 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
679 if (PrevClassTemplate)
680 PrevDecl = PrevClassTemplate->getTemplatedDecl();
681 }
682
683 if (!PrevClassTemplate && Qualifier) {
684 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000685 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
686 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000687 return 0;
688 }
689
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000690 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000691 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000692 bool Complain = true;
693
694 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
695 // template for struct std::tr1::__detail::_Map_base, where the
696 // template parameters of the friend declaration don't match the
697 // template parameters of the original declaration. In this one
698 // case, we don't complain about the ill-formed friend
699 // declaration.
700 if (isFriend && Pattern->getIdentifier() &&
701 Pattern->getIdentifier()->isStr("_Map_base") &&
702 DC->isNamespace() &&
703 cast<NamespaceDecl>(DC)->getIdentifier() &&
704 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
705 DeclContext *DCParent = DC->getParent();
706 if (DCParent->isNamespace() &&
707 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
708 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
709 DeclContext *DCParent2 = DCParent->getParent();
710 if (DCParent2->isNamespace() &&
711 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
712 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
713 DCParent2->getParent()->isTranslationUnit())
714 Complain = false;
715 }
716 }
717
John McCall93ba8572010-03-25 06:39:04 +0000718 TemplateParameterList *PrevParams
719 = PrevClassTemplate->getTemplateParameters();
720
721 // Make sure the parameter lists match.
722 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000723 Complain,
724 Sema::TPL_TemplateMatch)) {
725 if (Complain)
726 return 0;
727
728 AdoptedPreviousTemplateParams = true;
729 InstParams = PrevParams;
730 }
John McCall93ba8572010-03-25 06:39:04 +0000731
732 // Do some additional validation, then merge default arguments
733 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000734 if (!AdoptedPreviousTemplateParams &&
735 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000736 Sema::TPC_ClassTemplate))
737 return 0;
738 }
739 }
740
John McCalle29ba202009-08-20 01:44:21 +0000741 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000742 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000743 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000744 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000745 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000746
John McCall93ba8572010-03-25 06:39:04 +0000747 if (Qualifier)
748 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000749
John McCalle29ba202009-08-20 01:44:21 +0000750 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000751 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
752 D->getIdentifier(), InstParams, RecordInst,
753 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000754 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000755
John McCall93ba8572010-03-25 06:39:04 +0000756 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000757 if (PrevClassTemplate)
758 Inst->setAccess(PrevClassTemplate->getAccess());
759 else
760 Inst->setAccess(D->getAccess());
761
John McCall93ba8572010-03-25 06:39:04 +0000762 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
763 // TODO: do we want to track the instantiation progeny of this
764 // friend target decl?
765 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000766 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000767 Inst->setInstantiatedFromMemberTemplate(D);
768 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000769
770 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000771 SemaRef.Context.getInjectedClassNameType(RecordInst,
772 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000773
Douglas Gregor259571e2009-10-30 22:42:42 +0000774 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000775 if (isFriend) {
776 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000777 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000778 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000779
John McCalle29ba202009-08-20 01:44:21 +0000780 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000781
Douglas Gregored9c0f92009-10-29 00:04:11 +0000782 // Instantiate all of the partial specializations of this member class
783 // template.
Douglas Gregordc60c1e2010-04-30 05:56:50 +0000784 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
785 D->getPartialSpecializations(PartialSpecs);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000786 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
787 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
788
John McCalle29ba202009-08-20 01:44:21 +0000789 return Inst;
790}
791
Douglas Gregord60e1052009-08-27 16:57:43 +0000792Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000793TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
794 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000795 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
796
797 // Lookup the already-instantiated declaration in the instantiation
798 // of the class template and return that.
799 DeclContext::lookup_result Found
800 = Owner->lookup(ClassTemplate->getDeclName());
801 if (Found.first == Found.second)
802 return 0;
803
804 ClassTemplateDecl *InstClassTemplate
805 = dyn_cast<ClassTemplateDecl>(*Found.first);
806 if (!InstClassTemplate)
807 return 0;
808
809 Decl *DCanon = D->getCanonicalDecl();
810 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
811 P = InstClassTemplate->getPartialSpecializations().begin(),
812 PEnd = InstClassTemplate->getPartialSpecializations().end();
813 P != PEnd; ++P) {
814 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
815 return &*P;
816 }
817
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000818 return 0;
819}
820
821Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000822TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000823 // Create a local instantiation scope for this function template, which
824 // will contain the instantiations of the template parameters and then get
825 // merged with the local instantiation scope for the function template
826 // itself.
827 Sema::LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000828
Douglas Gregord60e1052009-08-27 16:57:43 +0000829 TemplateParameterList *TempParams = D->getTemplateParameters();
830 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000831 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000832 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000833
Douglas Gregora735b202009-10-13 14:39:41 +0000834 FunctionDecl *Instantiated = 0;
835 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
836 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
837 InstParams));
838 else
839 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
840 D->getTemplatedDecl(),
841 InstParams));
842
843 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000844 return 0;
845
John McCall46460a62010-01-20 21:53:11 +0000846 Instantiated->setAccess(D->getAccess());
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000849 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000850 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000851 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000852 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000853 assert(InstTemplate &&
854 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000855
John McCallb1a56e72010-03-26 23:10:15 +0000856 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
857
John McCalle976ffe2009-12-14 23:19:40 +0000858 // Link the instantiation back to the pattern *unless* this is a
859 // non-definition friend declaration.
860 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000861 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000862 InstTemplate->setInstantiatedFromMemberTemplate(D);
863
John McCallb1a56e72010-03-26 23:10:15 +0000864 // Make declarations visible in the appropriate context.
865 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000866 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000867
Douglas Gregord60e1052009-08-27 16:57:43 +0000868 return InstTemplate;
869}
870
Douglas Gregord475b8d2009-03-25 21:17:03 +0000871Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
872 CXXRecordDecl *PrevDecl = 0;
873 if (D->isInjectedClassName())
874 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000875 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000876 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
877 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000878 TemplateArgs);
879 if (!Prev) return 0;
880 PrevDecl = cast<CXXRecordDecl>(Prev);
881 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000882
883 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000884 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000885 D->getLocation(), D->getIdentifier(),
886 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000887
888 // Substitute the nested name specifier, if any.
889 if (SubstQualifier(D, Record))
890 return 0;
891
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000893 // FIXME: Check against AS_none is an ugly hack to work around the issue that
894 // the tag decls introduced by friend class declarations don't have an access
895 // specifier. Remove once this area of the code gets sorted out.
896 if (D->getAccess() != AS_none)
897 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000898 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000899 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000900
John McCall02cace72009-08-28 07:59:38 +0000901 // If the original function was part of a friend declaration,
902 // inherit its namespace state.
903 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
904 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
905
Anders Carlssond8b285f2009-09-01 04:26:58 +0000906 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
907
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000908 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000909 return Record;
910}
911
John McCall02cace72009-08-28 07:59:38 +0000912/// Normal class members are of more specific types and therefore
913/// don't make it here. This function serves two purposes:
914/// 1) instantiating function templates
915/// 2) substituting friend declarations
916/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000917Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000918 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000919 // Check whether there is already a function template specialization for
920 // this declaration.
921 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
922 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000923 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000924 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000925 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000926 TemplateArgs.getInnermost().getFlatArgumentList(),
927 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000928 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000929
930 FunctionTemplateSpecializationInfo *Info
931 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000932 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Douglas Gregor127102b2009-06-29 20:59:39 +0000934 // If we already have a function template specialization, return it.
935 if (Info)
936 return Info->Function;
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
John McCallb0cb0222010-03-27 05:57:59 +0000939 bool isFriend;
940 if (FunctionTemplate)
941 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
942 else
943 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
944
Douglas Gregor79c22782010-01-16 20:21:20 +0000945 bool MergeWithParentScope = (TemplateParams != 0) ||
946 !(isa<Decl>(Owner) &&
947 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
948 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Douglas Gregore53060f2009-06-25 22:08:12 +0000950 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000951 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
952 TInfo = SubstFunctionType(D, Params);
953 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000954 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000955 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000956
John McCalld325daa2010-03-26 04:53:08 +0000957 NestedNameSpecifier *Qualifier = D->getQualifier();
958 if (Qualifier) {
959 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
960 D->getQualifierRange(),
961 TemplateArgs);
962 if (!Qualifier) return 0;
963 }
964
John McCall68b6b872010-02-06 01:50:47 +0000965 // If we're instantiating a local function declaration, put the result
966 // in the owner; otherwise we need to find the instantiated context.
967 DeclContext *DC;
968 if (D->getDeclContext()->isFunctionOrMethod())
969 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000970 else if (isFriend && Qualifier) {
971 CXXScopeSpec SS;
972 SS.setScopeRep(Qualifier);
973 SS.setRange(D->getQualifierRange());
974 DC = SemaRef.computeDeclContext(SS);
975 if (!DC) return 0;
976 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000977 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
978 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000979 }
John McCall68b6b872010-02-06 01:50:47 +0000980
John McCall02cace72009-08-28 07:59:38 +0000981 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000982 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000983 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000984 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000985 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000986
John McCalld325daa2010-03-26 04:53:08 +0000987 if (Qualifier)
988 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000989
John McCallb1a56e72010-03-26 23:10:15 +0000990 DeclContext *LexicalDC = Owner;
991 if (!isFriend && D->isOutOfLine()) {
992 assert(D->getDeclContext()->isFileContext());
993 LexicalDC = D->getDeclContext();
994 }
995
996 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Douglas Gregore53060f2009-06-25 22:08:12 +0000998 // Attach the parameters
999 for (unsigned P = 0; P < Params.size(); ++P)
1000 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001001 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001002
Douglas Gregora735b202009-10-13 14:39:41 +00001003 if (TemplateParams) {
1004 // Our resulting instantiation is actually a function template, since we
1005 // are substituting only the outer template parameters. For example, given
1006 //
1007 // template<typename T>
1008 // struct X {
1009 // template<typename U> friend void f(T, U);
1010 // };
1011 //
1012 // X<int> x;
1013 //
1014 // We are instantiating the friend function template "f" within X<int>,
1015 // which means substituting int for T, but leaving "f" as a friend function
1016 // template.
1017 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001018 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001019 Function->getLocation(),
1020 Function->getDeclName(),
1021 TemplateParams, Function);
1022 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001023
1024 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001025
1026 if (isFriend && D->isThisDeclarationADefinition()) {
1027 // TODO: should we remember this connection regardless of whether
1028 // the friend declaration provided a body?
1029 FunctionTemplate->setInstantiatedFromMemberTemplate(
1030 D->getDescribedFunctionTemplate());
1031 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001032 } else if (FunctionTemplate) {
1033 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001034 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001035 &TemplateArgs.getInnermost(),
1036 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001037 } else if (isFriend && D->isThisDeclarationADefinition()) {
1038 // TODO: should we remember this connection regardless of whether
1039 // the friend declaration provided a body?
1040 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001041 }
Douglas Gregora735b202009-10-13 14:39:41 +00001042
Douglas Gregore53060f2009-06-25 22:08:12 +00001043 if (InitFunctionInstantiation(Function, D))
1044 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregore53060f2009-06-25 22:08:12 +00001046 bool Redeclaration = false;
1047 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001048 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001049
John McCall68263142009-11-18 22:49:29 +00001050 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1051 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1052
John McCallaf2094e2010-04-08 09:05:18 +00001053 if (DependentFunctionTemplateSpecializationInfo *Info
1054 = D->getDependentSpecializationInfo()) {
1055 assert(isFriend && "non-friend has dependent specialization info?");
1056
1057 // This needs to be set now for future sanity.
1058 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1059
1060 // Instantiate the explicit template arguments.
1061 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1062 Info->getRAngleLoc());
1063 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1064 TemplateArgumentLoc Loc;
1065 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1066 return 0;
1067
1068 ExplicitArgs.addArgument(Loc);
1069 }
1070
1071 // Map the candidate templates to their instantiations.
1072 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1073 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1074 Info->getTemplate(I),
1075 TemplateArgs);
1076 if (!Temp) return 0;
1077
1078 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1079 }
1080
1081 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1082 &ExplicitArgs,
1083 Previous))
1084 Function->setInvalidDecl();
1085
1086 isExplicitSpecialization = true;
1087
1088 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001089 // Look only into the namespace where the friend would be declared to
1090 // find a previous declaration. This is the innermost enclosing namespace,
1091 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001092 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001093
Douglas Gregora735b202009-10-13 14:39:41 +00001094 // In C++, the previous declaration we find might be a tag type
1095 // (class or enum). In this case, the new declaration will hide the
1096 // tag type. Note that this does does not apply if we're declaring a
1097 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001098 if (Previous.isSingleTagDecl())
1099 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001100 }
1101
John McCall9f54ad42009-12-10 09:41:52 +00001102 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001103 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001104 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001105
John McCall76d32642010-04-24 01:30:58 +00001106 NamedDecl *PrincipalDecl = (TemplateParams
1107 ? cast<NamedDecl>(FunctionTemplate)
1108 : Function);
1109
Douglas Gregora735b202009-10-13 14:39:41 +00001110 // If the original function was part of a friend declaration,
1111 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001112 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001113 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001114 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001115 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001116 else
Douglas Gregora735b202009-10-13 14:39:41 +00001117 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001118
1119 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1120 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001121 }
1122
John McCall76d32642010-04-24 01:30:58 +00001123 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1124 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1125 PrincipalDecl->setNonMemberOperator();
1126
Douglas Gregore53060f2009-06-25 22:08:12 +00001127 return Function;
1128}
1129
Douglas Gregord60e1052009-08-27 16:57:43 +00001130Decl *
1131TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1132 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001133 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1134 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001135 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001136 // We are creating a function template specialization from a function
1137 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001138 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001139 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001140 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001141 TemplateArgs.getInnermost().getFlatArgumentList(),
1142 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001143 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001144
1145 FunctionTemplateSpecializationInfo *Info
1146 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001147 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Douglas Gregor6b906862009-08-21 00:16:32 +00001149 // If we already have a function template specialization, return it.
1150 if (Info)
1151 return Info->Function;
1152 }
1153
John McCallb0cb0222010-03-27 05:57:59 +00001154 bool isFriend;
1155 if (FunctionTemplate)
1156 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1157 else
1158 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1159
Douglas Gregor79c22782010-01-16 20:21:20 +00001160 bool MergeWithParentScope = (TemplateParams != 0) ||
1161 !(isa<Decl>(Owner) &&
1162 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1163 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001164
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001165 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001166 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1167 TInfo = SubstFunctionType(D, Params);
1168 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001169 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001170 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001171
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001172 // \brief If the type of this function is not *directly* a function
1173 // type, then we're instantiating the a function that was declared
1174 // via a typedef, e.g.,
1175 //
1176 // typedef int functype(int, int);
1177 // functype func;
1178 //
1179 // In this case, we'll just go instantiate the ParmVarDecls that we
1180 // synthesized in the method declaration.
1181 if (!isa<FunctionProtoType>(T)) {
1182 assert(!Params.size() && "Instantiating type could not yield parameters");
1183 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1184 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1185 TemplateArgs);
1186 if (!P)
1187 return 0;
1188
1189 Params.push_back(P);
1190 }
1191 }
1192
John McCallb0cb0222010-03-27 05:57:59 +00001193 NestedNameSpecifier *Qualifier = D->getQualifier();
1194 if (Qualifier) {
1195 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1196 D->getQualifierRange(),
1197 TemplateArgs);
1198 if (!Qualifier) return 0;
1199 }
1200
1201 DeclContext *DC = Owner;
1202 if (isFriend) {
1203 if (Qualifier) {
1204 CXXScopeSpec SS;
1205 SS.setScopeRep(Qualifier);
1206 SS.setRange(D->getQualifierRange());
1207 DC = SemaRef.computeDeclContext(SS);
1208 } else {
1209 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1210 D->getDeclContext(),
1211 TemplateArgs);
1212 }
1213 if (!DC) return 0;
1214 }
1215
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001216 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001217 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001218 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Douglas Gregordec06662009-08-21 18:42:58 +00001220 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001221 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001222 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1223 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1224 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001225 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1226 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001227 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001228 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001229 Constructor->isInlineSpecified(),
1230 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001231 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1232 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1233 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1234 SemaRef.Context.getCanonicalType(ClassTy));
1235 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1236 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001237 T, Destructor->isInlineSpecified(),
1238 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001239 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001240 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001241 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001242 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001243 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1244 ConvTy);
1245 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1246 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001247 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001248 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001249 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001250 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001251 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001252 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001253 D->isStatic(),
1254 D->getStorageClassAsWritten(),
1255 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001256 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001257
John McCallb0cb0222010-03-27 05:57:59 +00001258 if (Qualifier)
1259 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001260
Douglas Gregord60e1052009-08-27 16:57:43 +00001261 if (TemplateParams) {
1262 // Our resulting instantiation is actually a function template, since we
1263 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001264 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001265 // template<typename T>
1266 // struct X {
1267 // template<typename U> void f(T, U);
1268 // };
1269 //
1270 // X<int> x;
1271 //
1272 // We are instantiating the member template "f" within X<int>, which means
1273 // substituting int for T, but leaving "f" as a member function template.
1274 // Build the function template itself.
1275 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1276 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001277 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001278 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001279 if (isFriend) {
1280 FunctionTemplate->setLexicalDeclContext(Owner);
1281 FunctionTemplate->setObjectOfFriendDecl(true);
1282 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001283 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001284 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001285 } else if (FunctionTemplate) {
1286 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001287 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001288 &TemplateArgs.getInnermost(),
1289 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001290 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001291 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001292 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001293 }
1294
Mike Stump1eb44332009-09-09 15:08:12 +00001295 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001296 // out-of-line, the instantiation will have the same lexical
1297 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001298 if (isFriend) {
1299 Method->setLexicalDeclContext(Owner);
1300 Method->setObjectOfFriendDecl(true);
1301 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001302 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Douglas Gregor5545e162009-03-24 00:38:23 +00001304 // Attach the parameters
1305 for (unsigned P = 0; P < Params.size(); ++P)
1306 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001307 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001308
1309 if (InitMethodInstantiation(Method, D))
1310 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001311
John McCall68263142009-11-18 22:49:29 +00001312 LookupResult Previous(SemaRef, Name, SourceLocation(),
1313 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
John McCallb0cb0222010-03-27 05:57:59 +00001315 if (!FunctionTemplate || TemplateParams || isFriend) {
1316 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Douglas Gregordec06662009-08-21 18:42:58 +00001318 // In C++, the previous declaration we find might be a tag type
1319 // (class or enum). In this case, the new declaration will hide the
1320 // tag type. Note that this does does not apply if we're declaring a
1321 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001322 if (Previous.isSingleTagDecl())
1323 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001324 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001325
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001326 bool Redeclaration = false;
1327 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001328 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001329 /*FIXME:*/OverloadableAttrRequired);
1330
Douglas Gregor4ba31362009-12-01 17:24:26 +00001331 if (D->isPure())
1332 SemaRef.CheckPureMethod(Method, SourceRange());
1333
John McCall46460a62010-01-20 21:53:11 +00001334 Method->setAccess(D->getAccess());
1335
John McCallb0cb0222010-03-27 05:57:59 +00001336 if (FunctionTemplate) {
1337 // If there's a function template, let our caller handle it.
1338 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1339 // Don't hide a (potentially) valid declaration with an invalid one.
1340 } else {
1341 NamedDecl *DeclToAdd = (TemplateParams
1342 ? cast<NamedDecl>(FunctionTemplate)
1343 : Method);
1344 if (isFriend)
1345 Record->makeDeclVisibleInContext(DeclToAdd);
1346 else
1347 Owner->addDecl(DeclToAdd);
1348 }
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001350 return Method;
1351}
1352
Douglas Gregor615c5d42009-03-24 16:43:20 +00001353Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001354 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001355}
1356
Douglas Gregor03b2b072009-03-24 00:15:49 +00001357Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001358 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001359}
1360
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001361Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001362 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001363}
1364
Douglas Gregor6477b692009-03-25 15:04:13 +00001365ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001366 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001367}
1368
John McCalle29ba202009-08-20 01:44:21 +00001369Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1370 TemplateTypeParmDecl *D) {
1371 // TODO: don't always clone when decls are refcounted.
1372 const Type* T = D->getTypeForDecl();
1373 assert(T->isTemplateTypeParmType());
1374 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001375
John McCalle29ba202009-08-20 01:44:21 +00001376 TemplateTypeParmDecl *Inst =
1377 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001378 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001379 TTPT->getName(),
1380 D->wasDeclaredWithTypename(),
1381 D->isParameterPack());
1382
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001383 if (D->hasDefaultArgument())
1384 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001385
Douglas Gregor550d9b22009-10-31 17:21:17 +00001386 // Introduce this template parameter's instantiation into the instantiation
1387 // scope.
1388 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1389
John McCalle29ba202009-08-20 01:44:21 +00001390 return Inst;
1391}
1392
Douglas Gregor33642df2009-10-23 23:25:44 +00001393Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1394 NonTypeTemplateParmDecl *D) {
1395 // Substitute into the type of the non-type template parameter.
1396 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001397 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001398 if (DI) {
1399 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1400 D->getDeclName());
1401 if (DI) T = DI->getType();
1402 } else {
1403 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1404 D->getDeclName());
1405 DI = 0;
1406 }
1407 if (T.isNull())
1408 return 0;
1409
1410 // Check that this type is acceptable for a non-type template parameter.
1411 bool Invalid = false;
1412 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1413 if (T.isNull()) {
1414 T = SemaRef.Context.IntTy;
1415 Invalid = true;
1416 }
1417
1418 NonTypeTemplateParmDecl *Param
1419 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1420 D->getDepth() - 1, D->getPosition(),
1421 D->getIdentifier(), T, DI);
1422 if (Invalid)
1423 Param->setInvalidDecl();
1424
1425 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001426
1427 // Introduce this template parameter's instantiation into the instantiation
1428 // scope.
1429 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001430 return Param;
1431}
1432
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001433Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001434TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1435 TemplateTemplateParmDecl *D) {
1436 // Instantiate the template parameter list of the template template parameter.
1437 TemplateParameterList *TempParams = D->getTemplateParameters();
1438 TemplateParameterList *InstParams;
1439 {
1440 // Perform the actual substitution of template parameters within a new,
1441 // local instantiation scope.
1442 Sema::LocalInstantiationScope Scope(SemaRef);
1443 InstParams = SubstTemplateParams(TempParams);
1444 if (!InstParams)
1445 return NULL;
1446 }
1447
1448 // Build the template template parameter.
1449 TemplateTemplateParmDecl *Param
1450 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1451 D->getDepth() - 1, D->getPosition(),
1452 D->getIdentifier(), InstParams);
1453 Param->setDefaultArgument(D->getDefaultArgument());
1454
1455 // Introduce this template parameter's instantiation into the instantiation
1456 // scope.
1457 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1458
1459 return Param;
1460}
1461
Douglas Gregor48c32a72009-11-17 06:07:40 +00001462Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1463 // Using directives are never dependent, so they require no explicit
1464
1465 UsingDirectiveDecl *Inst
1466 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1467 D->getNamespaceKeyLocation(),
1468 D->getQualifierRange(), D->getQualifier(),
1469 D->getIdentLocation(),
1470 D->getNominatedNamespace(),
1471 D->getCommonAncestor());
1472 Owner->addDecl(Inst);
1473 return Inst;
1474}
1475
John McCalled976492009-12-04 22:46:56 +00001476Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1477 // The nested name specifier is non-dependent, so no transformation
1478 // is required.
1479
John McCall9f54ad42009-12-10 09:41:52 +00001480 // We only need to do redeclaration lookups if we're in a class
1481 // scope (in fact, it's not really even possible in non-class
1482 // scopes).
1483 bool CheckRedeclaration = Owner->isRecord();
1484
1485 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1486 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1487
John McCalled976492009-12-04 22:46:56 +00001488 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1489 D->getLocation(),
1490 D->getNestedNameRange(),
1491 D->getUsingLocation(),
1492 D->getTargetNestedNameDecl(),
1493 D->getDeclName(),
1494 D->isTypeName());
1495
1496 CXXScopeSpec SS;
1497 SS.setScopeRep(D->getTargetNestedNameDecl());
1498 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001499
1500 if (CheckRedeclaration) {
1501 Prev.setHideTags(false);
1502 SemaRef.LookupQualifiedName(Prev, Owner);
1503
1504 // Check for invalid redeclarations.
1505 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1506 D->isTypeName(), SS,
1507 D->getLocation(), Prev))
1508 NewUD->setInvalidDecl();
1509
1510 }
1511
1512 if (!NewUD->isInvalidDecl() &&
1513 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001514 D->getLocation()))
1515 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001516
John McCalled976492009-12-04 22:46:56 +00001517 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1518 NewUD->setAccess(D->getAccess());
1519 Owner->addDecl(NewUD);
1520
John McCall9f54ad42009-12-10 09:41:52 +00001521 // Don't process the shadow decls for an invalid decl.
1522 if (NewUD->isInvalidDecl())
1523 return NewUD;
1524
John McCall323c3102009-12-22 22:26:37 +00001525 bool isFunctionScope = Owner->isFunctionOrMethod();
1526
John McCall9f54ad42009-12-10 09:41:52 +00001527 // Process the shadow decls.
1528 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1529 I != E; ++I) {
1530 UsingShadowDecl *Shadow = *I;
1531 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001532 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1533 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001534 TemplateArgs));
1535
1536 if (CheckRedeclaration &&
1537 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1538 continue;
1539
1540 UsingShadowDecl *InstShadow
1541 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1542 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001543
1544 if (isFunctionScope)
1545 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001546 }
John McCalled976492009-12-04 22:46:56 +00001547
1548 return NewUD;
1549}
1550
1551Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001552 // Ignore these; we handle them in bulk when processing the UsingDecl.
1553 return 0;
John McCalled976492009-12-04 22:46:56 +00001554}
1555
John McCall7ba107a2009-11-18 02:36:19 +00001556Decl * TemplateDeclInstantiator
1557 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001558 NestedNameSpecifier *NNS =
1559 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1560 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001561 TemplateArgs);
1562 if (!NNS)
1563 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001565 CXXScopeSpec SS;
1566 SS.setRange(D->getTargetNestedNameRange());
1567 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
1569 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001570 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001571 D->getUsingLoc(), SS, D->getLocation(),
1572 D->getDeclName(), 0,
1573 /*instantiation*/ true,
1574 /*typename*/ true, D->getTypenameLoc());
1575 if (UD)
John McCalled976492009-12-04 22:46:56 +00001576 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1577
John McCall7ba107a2009-11-18 02:36:19 +00001578 return UD;
1579}
1580
1581Decl * TemplateDeclInstantiator
1582 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1583 NestedNameSpecifier *NNS =
1584 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1585 D->getTargetNestedNameRange(),
1586 TemplateArgs);
1587 if (!NNS)
1588 return 0;
1589
1590 CXXScopeSpec SS;
1591 SS.setRange(D->getTargetNestedNameRange());
1592 SS.setScopeRep(NNS);
1593
1594 NamedDecl *UD =
1595 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1596 D->getUsingLoc(), SS, D->getLocation(),
1597 D->getDeclName(), 0,
1598 /*instantiation*/ true,
1599 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001600 if (UD)
John McCalled976492009-12-04 22:46:56 +00001601 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1602
Anders Carlsson0d8df782009-08-29 19:37:28 +00001603 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001604}
1605
John McCallce3ff2b2009-08-25 22:02:44 +00001606Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001607 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001608 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001609 if (D->isInvalidDecl())
1610 return 0;
1611
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001612 return Instantiator.Visit(D);
1613}
1614
John McCalle29ba202009-08-20 01:44:21 +00001615/// \brief Instantiates a nested template parameter list in the current
1616/// instantiation context.
1617///
1618/// \param L The parameter list to instantiate
1619///
1620/// \returns NULL if there was an error
1621TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001622TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001623 // Get errors for all the parameters before bailing out.
1624 bool Invalid = false;
1625
1626 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001627 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001628 ParamVector Params;
1629 Params.reserve(N);
1630 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1631 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001632 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001633 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001634 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001635 }
1636
1637 // Clean up if we had an error.
1638 if (Invalid) {
1639 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1640 PI != PE; ++PI)
1641 if (*PI)
1642 (*PI)->Destroy(SemaRef.Context);
1643 return NULL;
1644 }
1645
1646 TemplateParameterList *InstL
1647 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1648 L->getLAngleLoc(), &Params.front(), N,
1649 L->getRAngleLoc());
1650 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001651}
John McCalle29ba202009-08-20 01:44:21 +00001652
Douglas Gregored9c0f92009-10-29 00:04:11 +00001653/// \brief Instantiate the declaration of a class template partial
1654/// specialization.
1655///
1656/// \param ClassTemplate the (instantiated) class template that is partially
1657// specialized by the instantiation of \p PartialSpec.
1658///
1659/// \param PartialSpec the (uninstantiated) class template partial
1660/// specialization that we are instantiating.
1661///
1662/// \returns true if there was an error, false otherwise.
1663bool
1664TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1665 ClassTemplateDecl *ClassTemplate,
1666 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001667 // Create a local instantiation scope for this class template partial
1668 // specialization, which will contain the instantiations of the template
1669 // parameters.
1670 Sema::LocalInstantiationScope Scope(SemaRef);
1671
Douglas Gregored9c0f92009-10-29 00:04:11 +00001672 // Substitute into the template parameters of the class template partial
1673 // specialization.
1674 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1675 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1676 if (!InstParams)
1677 return true;
1678
1679 // Substitute into the template arguments of the class template partial
1680 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001681 const TemplateArgumentLoc *PartialSpecTemplateArgs
1682 = PartialSpec->getTemplateArgsAsWritten();
1683 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1684
John McCalld5532b62009-11-23 01:53:49 +00001685 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001686 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001687 TemplateArgumentLoc Loc;
1688 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001689 return true;
John McCalld5532b62009-11-23 01:53:49 +00001690 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001691 }
1692
1693
1694 // Check that the template argument list is well-formed for this
1695 // class template.
1696 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1697 InstTemplateArgs.size());
1698 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1699 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001700 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001701 false,
1702 Converted))
1703 return true;
1704
1705 // Figure out where to insert this class template partial specialization
1706 // in the member template's set of class template partial specializations.
1707 llvm::FoldingSetNodeID ID;
1708 ClassTemplatePartialSpecializationDecl::Profile(ID,
1709 Converted.getFlatArguments(),
1710 Converted.flatSize(),
1711 SemaRef.Context);
1712 void *InsertPos = 0;
1713 ClassTemplateSpecializationDecl *PrevDecl
1714 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1715 InsertPos);
1716
1717 // Build the canonical type that describes the converted template
1718 // arguments of the class template partial specialization.
1719 QualType CanonType
1720 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1721 Converted.getFlatArguments(),
1722 Converted.flatSize());
1723
1724 // Build the fully-sugared type for this class template
1725 // specialization as the user wrote in the specialization
1726 // itself. This means that we'll pretty-print the type retrieved
1727 // from the specialization's declaration the way that the user
1728 // actually wrote the specialization, rather than formatting the
1729 // name based on the "canonical" representation used to store the
1730 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001731 TypeSourceInfo *WrittenTy
1732 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1733 TemplateName(ClassTemplate),
1734 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001735 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001736 CanonType);
1737
1738 if (PrevDecl) {
1739 // We've already seen a partial specialization with the same template
1740 // parameters and template arguments. This can happen, for example, when
1741 // substituting the outer template arguments ends up causing two
1742 // class template partial specializations of a member class template
1743 // to have identical forms, e.g.,
1744 //
1745 // template<typename T, typename U>
1746 // struct Outer {
1747 // template<typename X, typename Y> struct Inner;
1748 // template<typename Y> struct Inner<T, Y>;
1749 // template<typename Y> struct Inner<U, Y>;
1750 // };
1751 //
1752 // Outer<int, int> outer; // error: the partial specializations of Inner
1753 // // have the same signature.
1754 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1755 << WrittenTy;
1756 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1757 << SemaRef.Context.getTypeDeclType(PrevDecl);
1758 return true;
1759 }
1760
1761
1762 // Create the class template partial specialization declaration.
1763 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001764 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1765 PartialSpec->getTagKind(),
1766 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001767 PartialSpec->getLocation(),
1768 InstParams,
1769 ClassTemplate,
1770 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001771 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001772 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001773 0,
1774 ClassTemplate->getPartialSpecializations().size());
John McCallb6217662010-03-15 10:12:16 +00001775 // Substitute the nested name specifier, if any.
1776 if (SubstQualifier(PartialSpec, InstPartialSpec))
1777 return 0;
1778
Douglas Gregored9c0f92009-10-29 00:04:11 +00001779 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1780 InstPartialSpec->setTypeAsWritten(WrittenTy);
1781
1782 // Add this partial specialization to the set of class template partial
1783 // specializations.
1784 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1785 InsertPos);
1786 return false;
1787}
1788
John McCall21ef0fa2010-03-11 09:03:00 +00001789TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001790TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001791 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001792 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1793 assert(OldTInfo && "substituting function without type source info");
1794 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001795 TypeSourceInfo *NewTInfo
1796 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1797 D->getTypeSpecStartLoc(),
1798 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001799 if (!NewTInfo)
1800 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001801
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001802 if (NewTInfo != OldTInfo) {
1803 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001804 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001805 if (FunctionProtoTypeLoc *OldProtoLoc
1806 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1807 TypeLoc NewTL = NewTInfo->getTypeLoc();
1808 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1809 assert(NewProtoLoc && "Missing prototype?");
1810 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1811 // FIXME: Variadic templates will break this.
1812 Params.push_back(NewProtoLoc->getArg(i));
1813 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001814 OldProtoLoc->getArg(i),
1815 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001816 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001817 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001818 } else {
1819 // The function type itself was not dependent and therefore no
1820 // substitution occurred. However, we still need to instantiate
1821 // the function parameters themselves.
1822 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001823 if (FunctionProtoTypeLoc *OldProtoLoc
1824 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1825 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1826 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1827 if (!Parm)
1828 return 0;
1829 Params.push_back(Parm);
1830 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001831 }
1832 }
John McCall21ef0fa2010-03-11 09:03:00 +00001833 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001834}
1835
Mike Stump1eb44332009-09-09 15:08:12 +00001836/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001837/// declaration (New) from the corresponding fields of its template (Tmpl).
1838///
1839/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001840bool
1841TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001842 FunctionDecl *Tmpl) {
1843 if (Tmpl->isDeleted())
1844 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregorcca9e962009-07-01 22:01:06 +00001846 // If we are performing substituting explicitly-specified template arguments
1847 // or deduced template arguments into a function template and we reach this
1848 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001849 // to keeping the new function template specialization. We therefore
1850 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001851 // into a template instantiation for this specific function template
1852 // specialization, which is not a SFINAE context, so that we diagnose any
1853 // further errors in the declaration itself.
1854 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1855 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1856 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1857 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001858 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001859 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001860 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001861 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001862 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001863 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1864 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001865 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001866 }
1867 }
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001869 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1870 assert(Proto && "Function template without prototype?");
1871
1872 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1873 Proto->getNoReturnAttr()) {
1874 // The function has an exception specification or a "noreturn"
1875 // attribute. Substitute into each of the exception types.
1876 llvm::SmallVector<QualType, 4> Exceptions;
1877 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1878 // FIXME: Poor location information!
1879 QualType T
1880 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1881 New->getLocation(), New->getDeclName());
1882 if (T.isNull() ||
1883 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1884 continue;
1885
1886 Exceptions.push_back(T);
1887 }
1888
1889 // Rebuild the function type
1890
1891 const FunctionProtoType *NewProto
1892 = New->getType()->getAs<FunctionProtoType>();
1893 assert(NewProto && "Template instantiation without function prototype?");
1894 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1895 NewProto->arg_type_begin(),
1896 NewProto->getNumArgs(),
1897 NewProto->isVariadic(),
1898 NewProto->getTypeQuals(),
1899 Proto->hasExceptionSpec(),
1900 Proto->hasAnyExceptionSpec(),
1901 Exceptions.size(),
1902 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001903 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001904 }
1905
Douglas Gregore53060f2009-06-25 22:08:12 +00001906 return false;
1907}
1908
Douglas Gregor5545e162009-03-24 00:38:23 +00001909/// \brief Initializes common fields of an instantiated method
1910/// declaration (New) from the corresponding fields of its template
1911/// (Tmpl).
1912///
1913/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001914bool
1915TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001916 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001917 if (InitFunctionInstantiation(New, Tmpl))
1918 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Douglas Gregor5545e162009-03-24 00:38:23 +00001920 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1921 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001922 if (Tmpl->isVirtualAsWritten())
1923 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001924
1925 // FIXME: attributes
1926 // FIXME: New needs a pointer to Tmpl
1927 return false;
1928}
Douglas Gregora58861f2009-05-13 20:28:22 +00001929
1930/// \brief Instantiate the definition of the given function from its
1931/// template.
1932///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001933/// \param PointOfInstantiation the point at which the instantiation was
1934/// required. Note that this is not precisely a "point of instantiation"
1935/// for the function, but it's close.
1936///
Douglas Gregora58861f2009-05-13 20:28:22 +00001937/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001938/// function template specialization or member function of a class template
1939/// specialization.
1940///
1941/// \param Recursive if true, recursively instantiates any functions that
1942/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001943///
1944/// \param DefinitionRequired if true, then we are performing an explicit
1945/// instantiation where the body of the function is required. Complain if
1946/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001947void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001948 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001949 bool Recursive,
1950 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001951 if (Function->isInvalidDecl())
1952 return;
1953
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001954 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001956 // Never instantiate an explicit specialization.
1957 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1958 return;
1959
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001960 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001961 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001962 Stmt *Pattern = 0;
1963 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001964 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001965
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001966 if (!Pattern) {
1967 if (DefinitionRequired) {
1968 if (Function->getPrimaryTemplate())
1969 Diag(PointOfInstantiation,
1970 diag::err_explicit_instantiation_undefined_func_template)
1971 << Function->getPrimaryTemplate();
1972 else
1973 Diag(PointOfInstantiation,
1974 diag::err_explicit_instantiation_undefined_member)
1975 << 1 << Function->getDeclName() << Function->getDeclContext();
1976
1977 if (PatternDecl)
1978 Diag(PatternDecl->getLocation(),
1979 diag::note_explicit_instantiation_here);
1980 }
1981
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001982 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001983 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001984
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001985 // C++0x [temp.explicit]p9:
1986 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001987 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001988 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001989 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001990 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001991 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001992 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001994 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1995 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00001996 return;
1997
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001998 // If we're performing recursive template instantiation, create our own
1999 // queue of pending implicit instantiations that we will instantiate later,
2000 // while we're still within our own instantiation context.
2001 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2002 if (Recursive)
2003 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002005 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2006
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002007 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002008 // recorded, unless we're actually a member function within a local
2009 // class, in which case we need to merge our results with the parent
2010 // scope (of the enclosing function).
2011 bool MergeWithParentScope = false;
2012 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2013 MergeWithParentScope = Rec->isLocalClass();
2014
2015 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002017 // Introduce the instantiated function parameters into the local
2018 // instantiation scope.
2019 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2020 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2021 Function->getParamDecl(I));
2022
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002023 // Enter the scope of this instantiation. We don't use
2024 // PushDeclContext because we don't have a scope.
2025 DeclContext *PreviousContext = CurContext;
2026 CurContext = Function;
2027
Mike Stump1eb44332009-09-09 15:08:12 +00002028 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002029 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002030
2031 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002033 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2034 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2035 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002036 }
2037
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002038 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002039 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002040
Douglas Gregor52604ab2009-09-11 21:19:12 +00002041 if (Body.isInvalid())
2042 Function->setInvalidDecl();
2043
Mike Stump1eb44332009-09-09 15:08:12 +00002044 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002045 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002046
John McCall0c01d182010-03-24 05:22:00 +00002047 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2048
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002049 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002050
2051 DeclGroupRef DG(Function);
2052 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Douglas Gregor60406be2010-01-16 22:29:39 +00002054 // This class may have local implicit instantiations that need to be
2055 // instantiation within this scope.
2056 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2057 Scope.Exit();
2058
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002059 if (Recursive) {
2060 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002061 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002062 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002064 // Restore the set of pending implicit instantiations.
2065 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2066 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002067}
2068
2069/// \brief Instantiate the definition of the given variable from its
2070/// template.
2071///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002072/// \param PointOfInstantiation the point at which the instantiation was
2073/// required. Note that this is not precisely a "point of instantiation"
2074/// for the function, but it's close.
2075///
2076/// \param Var the already-instantiated declaration of a static member
2077/// variable of a class template specialization.
2078///
2079/// \param Recursive if true, recursively instantiates any functions that
2080/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002081///
2082/// \param DefinitionRequired if true, then we are performing an explicit
2083/// instantiation where an out-of-line definition of the member variable
2084/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002085void Sema::InstantiateStaticDataMemberDefinition(
2086 SourceLocation PointOfInstantiation,
2087 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002088 bool Recursive,
2089 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002090 if (Var->isInvalidDecl())
2091 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Douglas Gregor7caa6822009-07-24 20:34:43 +00002093 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002094 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002095 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002096 assert(Def->isStaticDataMember() && "Not a static data member?");
2097 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Douglas Gregor0d035142009-10-27 18:42:08 +00002099 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002100 // We did not find an out-of-line definition of this static data member,
2101 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002102 // instantiate this definition (or provide a specialization for it) in
2103 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002104 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002105 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002106 Diag(PointOfInstantiation,
2107 diag::err_explicit_instantiation_undefined_member)
2108 << 2 << Var->getDeclName() << Var->getDeclContext();
2109 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2110 }
2111
Douglas Gregor7caa6822009-07-24 20:34:43 +00002112 return;
2113 }
2114
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002115 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002116 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002117 return;
2118
2119 // C++0x [temp.explicit]p9:
2120 // Except for inline functions, other explicit instantiation declarations
2121 // have the effect of suppressing the implicit instantiation of the entity
2122 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002123 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002124 == TSK_ExplicitInstantiationDeclaration)
2125 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregor7caa6822009-07-24 20:34:43 +00002127 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2128 if (Inst)
2129 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Douglas Gregor7caa6822009-07-24 20:34:43 +00002131 // If we're performing recursive template instantiation, create our own
2132 // queue of pending implicit instantiations that we will instantiate later,
2133 // while we're still within our own instantiation context.
2134 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2135 if (Recursive)
2136 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Douglas Gregor7caa6822009-07-24 20:34:43 +00002138 // Enter the scope of this instantiation. We don't use
2139 // PushDeclContext because we don't have a scope.
2140 DeclContext *PreviousContext = CurContext;
2141 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002143 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002144 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002145 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002146 CurContext = PreviousContext;
2147
2148 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002149 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2150 assert(MSInfo && "Missing member specialization information?");
2151 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2152 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002153 DeclGroupRef DG(Var);
2154 Consumer.HandleTopLevelDecl(DG);
2155 }
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Douglas Gregor7caa6822009-07-24 20:34:43 +00002157 if (Recursive) {
2158 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002159 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002160 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Douglas Gregor7caa6822009-07-24 20:34:43 +00002162 // Restore the set of pending implicit instantiations.
2163 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002164 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002165}
Douglas Gregor815215d2009-05-27 05:35:12 +00002166
Anders Carlsson09025312009-08-29 05:16:22 +00002167void
2168Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2169 const CXXConstructorDecl *Tmpl,
2170 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Anders Carlsson09025312009-08-29 05:16:22 +00002172 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002173 bool AnyErrors = false;
2174
Anders Carlsson09025312009-08-29 05:16:22 +00002175 // Instantiate all the initializers.
2176 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002177 InitsEnd = Tmpl->init_end();
2178 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002179 CXXBaseOrMemberInitializer *Init = *Inits;
2180
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002181 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002182 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002183 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002185 // Instantiate the initializer.
2186 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2187 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2188 AnyErrors = true;
2189 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002190 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002191
Anders Carlsson09025312009-08-29 05:16:22 +00002192 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002193 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002194 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002195 TemplateArgs,
2196 Init->getSourceLocation(),
2197 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002198 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002199 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002200 New->setInvalidDecl();
2201 continue;
2202 }
2203
John McCalla93c9342009-12-07 02:54:59 +00002204 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002205 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002206 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002207 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002208 Init->getRParenLoc(),
2209 New->getParent());
2210 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002211 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002213 // Is this an anonymous union?
2214 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002215 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2216 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002217 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002218 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2219 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002220 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002221
2222 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002223 NewArgs.size(),
2224 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002225 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002226 Init->getRParenLoc());
2227 }
2228
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002229 if (NewInit.isInvalid()) {
2230 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002231 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002232 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002233 // FIXME: It would be nice if ASTOwningVector had a release function.
2234 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Anders Carlsson09025312009-08-29 05:16:22 +00002236 NewInits.push_back((MemInitTy *)NewInit.get());
2237 }
2238 }
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Anders Carlsson09025312009-08-29 05:16:22 +00002240 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002241 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002242 /*FIXME: ColonLoc */
2243 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002244 NewInits.data(), NewInits.size(),
2245 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002246}
2247
John McCall52a575a2009-08-29 08:11:13 +00002248// TODO: this could be templated if the various decl types used the
2249// same method name.
2250static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2251 ClassTemplateDecl *Instance) {
2252 Pattern = Pattern->getCanonicalDecl();
2253
2254 do {
2255 Instance = Instance->getCanonicalDecl();
2256 if (Pattern == Instance) return true;
2257 Instance = Instance->getInstantiatedFromMemberTemplate();
2258 } while (Instance);
2259
2260 return false;
2261}
2262
Douglas Gregor0d696532009-09-28 06:34:35 +00002263static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2264 FunctionTemplateDecl *Instance) {
2265 Pattern = Pattern->getCanonicalDecl();
2266
2267 do {
2268 Instance = Instance->getCanonicalDecl();
2269 if (Pattern == Instance) return true;
2270 Instance = Instance->getInstantiatedFromMemberTemplate();
2271 } while (Instance);
2272
2273 return false;
2274}
2275
Douglas Gregored9c0f92009-10-29 00:04:11 +00002276static bool
2277isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2278 ClassTemplatePartialSpecializationDecl *Instance) {
2279 Pattern
2280 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2281 do {
2282 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2283 Instance->getCanonicalDecl());
2284 if (Pattern == Instance)
2285 return true;
2286 Instance = Instance->getInstantiatedFromMember();
2287 } while (Instance);
2288
2289 return false;
2290}
2291
John McCall52a575a2009-08-29 08:11:13 +00002292static bool isInstantiationOf(CXXRecordDecl *Pattern,
2293 CXXRecordDecl *Instance) {
2294 Pattern = Pattern->getCanonicalDecl();
2295
2296 do {
2297 Instance = Instance->getCanonicalDecl();
2298 if (Pattern == Instance) return true;
2299 Instance = Instance->getInstantiatedFromMemberClass();
2300 } while (Instance);
2301
2302 return false;
2303}
2304
2305static bool isInstantiationOf(FunctionDecl *Pattern,
2306 FunctionDecl *Instance) {
2307 Pattern = Pattern->getCanonicalDecl();
2308
2309 do {
2310 Instance = Instance->getCanonicalDecl();
2311 if (Pattern == Instance) return true;
2312 Instance = Instance->getInstantiatedFromMemberFunction();
2313 } while (Instance);
2314
2315 return false;
2316}
2317
2318static bool isInstantiationOf(EnumDecl *Pattern,
2319 EnumDecl *Instance) {
2320 Pattern = Pattern->getCanonicalDecl();
2321
2322 do {
2323 Instance = Instance->getCanonicalDecl();
2324 if (Pattern == Instance) return true;
2325 Instance = Instance->getInstantiatedFromMemberEnum();
2326 } while (Instance);
2327
2328 return false;
2329}
2330
John McCalled976492009-12-04 22:46:56 +00002331static bool isInstantiationOf(UsingShadowDecl *Pattern,
2332 UsingShadowDecl *Instance,
2333 ASTContext &C) {
2334 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2335}
2336
2337static bool isInstantiationOf(UsingDecl *Pattern,
2338 UsingDecl *Instance,
2339 ASTContext &C) {
2340 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2341}
2342
John McCall7ba107a2009-11-18 02:36:19 +00002343static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2344 UsingDecl *Instance,
2345 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002346 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002347}
2348
2349static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002350 UsingDecl *Instance,
2351 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002352 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002353}
2354
John McCall52a575a2009-08-29 08:11:13 +00002355static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2356 VarDecl *Instance) {
2357 assert(Instance->isStaticDataMember());
2358
2359 Pattern = Pattern->getCanonicalDecl();
2360
2361 do {
2362 Instance = Instance->getCanonicalDecl();
2363 if (Pattern == Instance) return true;
2364 Instance = Instance->getInstantiatedFromStaticDataMember();
2365 } while (Instance);
2366
2367 return false;
2368}
2369
John McCalled976492009-12-04 22:46:56 +00002370// Other is the prospective instantiation
2371// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002372static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002373 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002374 if (UnresolvedUsingTypenameDecl *UUD
2375 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2376 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2377 return isInstantiationOf(UUD, UD, Ctx);
2378 }
2379 }
2380
2381 if (UnresolvedUsingValueDecl *UUD
2382 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002383 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2384 return isInstantiationOf(UUD, UD, Ctx);
2385 }
2386 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002387
Anders Carlsson0d8df782009-08-29 19:37:28 +00002388 return false;
2389 }
Mike Stump1eb44332009-09-09 15:08:12 +00002390
John McCall52a575a2009-08-29 08:11:13 +00002391 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2392 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002393
John McCall52a575a2009-08-29 08:11:13 +00002394 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2395 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002396
John McCall52a575a2009-08-29 08:11:13 +00002397 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2398 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002399
Douglas Gregor7caa6822009-07-24 20:34:43 +00002400 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002401 if (Var->isStaticDataMember())
2402 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2403
2404 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2405 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002406
Douglas Gregor0d696532009-09-28 06:34:35 +00002407 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2408 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2409
Douglas Gregored9c0f92009-10-29 00:04:11 +00002410 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2411 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2412 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2413 PartialSpec);
2414
Anders Carlssond8b285f2009-09-01 04:26:58 +00002415 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2416 if (!Field->getDeclName()) {
2417 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002418 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002419 cast<FieldDecl>(D);
2420 }
2421 }
Mike Stump1eb44332009-09-09 15:08:12 +00002422
John McCalled976492009-12-04 22:46:56 +00002423 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2424 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2425
2426 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2427 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2428
Douglas Gregor815215d2009-05-27 05:35:12 +00002429 return D->getDeclName() && isa<NamedDecl>(Other) &&
2430 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2431}
2432
2433template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002434static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002435 NamedDecl *D,
2436 ForwardIterator first,
2437 ForwardIterator last) {
2438 for (; first != last; ++first)
2439 if (isInstantiationOf(Ctx, D, *first))
2440 return cast<NamedDecl>(*first);
2441
2442 return 0;
2443}
2444
John McCall02cace72009-08-28 07:59:38 +00002445/// \brief Finds the instantiation of the given declaration context
2446/// within the current instantiation.
2447///
2448/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002449DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002450 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002451 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002452 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002453 return cast_or_null<DeclContext>(ID);
2454 } else return DC;
2455}
2456
Douglas Gregored961e72009-05-27 17:54:46 +00002457/// \brief Find the instantiation of the given declaration within the
2458/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002459///
2460/// This routine is intended to be used when \p D is a declaration
2461/// referenced from within a template, that needs to mapped into the
2462/// corresponding declaration within an instantiation. For example,
2463/// given:
2464///
2465/// \code
2466/// template<typename T>
2467/// struct X {
2468/// enum Kind {
2469/// KnownValue = sizeof(T)
2470/// };
2471///
2472/// bool getKind() const { return KnownValue; }
2473/// };
2474///
2475/// template struct X<int>;
2476/// \endcode
2477///
2478/// In the instantiation of X<int>::getKind(), we need to map the
2479/// EnumConstantDecl for KnownValue (which refers to
2480/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002481/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2482/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002483NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002484 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002485 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002486 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002487 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002488 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002489 // D is a local of some kind. Look into the map of local
2490 // declarations to their instantiations.
2491 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2492 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002493
Douglas Gregore95b4092009-09-16 18:34:49 +00002494 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2495 if (!Record->isDependentContext())
2496 return D;
2497
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002498 // If the RecordDecl is actually the injected-class-name or a
2499 // "templated" declaration for a class template, class template
2500 // partial specialization, or a member class of a class template,
2501 // substitute into the injected-class-name of the class template
2502 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002503 QualType T;
2504 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2505
2506 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002507 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002508 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2509 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002510 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002511
2512 // If we call SubstType with an InjectedClassNameType here we
2513 // can end up in an infinite loop.
2514 T = Context.getTypeDeclType(Record);
2515 assert(isa<InjectedClassNameType>(T) &&
2516 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002517 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002518 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002519
2520 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002521 // Substitute into the injected-class-name to get the type
2522 // corresponding to the instantiation we want, which may also be
2523 // the current instantiation (if we're in a template
2524 // definition). This substitution should never fail, since we
2525 // know we can instantiate the injected-class-name or we
2526 // wouldn't have gotten to the injected-class-name!
2527
2528 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2529 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002530 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2531 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2532
2533 if (!T->isDependentType()) {
2534 assert(T->isRecordType() && "Instantiation must produce a record type");
2535 return T->getAs<RecordType>()->getDecl();
2536 }
2537
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002538 // We are performing "partial" template instantiation to create
2539 // the member declarations for the members of a class template
2540 // specialization. Therefore, D is actually referring to something
2541 // in the current instantiation. Look through the current
2542 // context, which contains actual instantiations, to find the
2543 // instantiation of the "current instantiation" that D refers
2544 // to.
2545 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002546 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002547 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002548 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002549 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002550 if (isInstantiationOf(ClassTemplate,
2551 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002552 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002553
2554 if (!DC->isDependentContext())
2555 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002556 }
2557
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002558 // We're performing "instantiation" of a member of the current
2559 // instantiation while we are type-checking the
2560 // definition. Compute the declaration context and return that.
2561 assert(!SawNonDependentContext &&
2562 "No dependent context while instantiating record");
2563 DeclContext *DC = computeDeclContext(T);
2564 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002565 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002566 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002567 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002568
Douglas Gregore95b4092009-09-16 18:34:49 +00002569 // Fall through to deal with other dependent record types (e.g.,
2570 // anonymous unions in class templates).
2571 }
John McCall52a575a2009-08-29 08:11:13 +00002572
Douglas Gregore95b4092009-09-16 18:34:49 +00002573 if (!ParentDC->isDependentContext())
2574 return D;
2575
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002576 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002577 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002578 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Douglas Gregor815215d2009-05-27 05:35:12 +00002580 if (ParentDC != D->getDeclContext()) {
2581 // We performed some kind of instantiation in the parent context,
2582 // so now we need to look into the instantiated parent context to
2583 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002584
John McCall3cb0ebd2010-03-10 03:28:59 +00002585 // If our context used to be dependent, we may need to instantiate
2586 // it before performing lookup into that context.
2587 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002588 if (!Spec->isDependentContext()) {
2589 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002590 const RecordType *Tag = T->getAs<RecordType>();
2591 assert(Tag && "type of non-dependent record is not a RecordType");
2592 if (!Tag->isBeingDefined() &&
2593 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2594 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002595 }
2596 }
2597
Douglas Gregor815215d2009-05-27 05:35:12 +00002598 NamedDecl *Result = 0;
2599 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002600 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002601 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2602 } else {
2603 // Since we don't have a name for the entity we're looking for,
2604 // our only option is to walk through all of the declarations to
2605 // find that name. This will occur in a few cases:
2606 //
2607 // - anonymous struct/union within a template
2608 // - unnamed class/struct/union/enum within a template
2609 //
2610 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002611 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002612 ParentDC->decls_begin(),
2613 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002614 }
Mike Stump1eb44332009-09-09 15:08:12 +00002615
John McCall9f54ad42009-12-10 09:41:52 +00002616 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002617 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2618 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002619 && "Unable to find instantiation of declaration!");
2620
Douglas Gregor815215d2009-05-27 05:35:12 +00002621 D = Result;
2622 }
2623
Douglas Gregor815215d2009-05-27 05:35:12 +00002624 return D;
2625}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002626
Mike Stump1eb44332009-09-09 15:08:12 +00002627/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002628/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002629void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2630 while (!PendingLocalImplicitInstantiations.empty() ||
2631 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2632 PendingImplicitInstantiation Inst;
2633
2634 if (PendingLocalImplicitInstantiations.empty()) {
2635 Inst = PendingImplicitInstantiations.front();
2636 PendingImplicitInstantiations.pop_front();
2637 } else {
2638 Inst = PendingLocalImplicitInstantiations.front();
2639 PendingLocalImplicitInstantiations.pop_front();
2640 }
Mike Stump1eb44332009-09-09 15:08:12 +00002641
Douglas Gregor7caa6822009-07-24 20:34:43 +00002642 // Instantiate function definitions
2643 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002644 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002645 Function->getLocation(), *this,
2646 Context.getSourceManager(),
2647 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002649 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002650 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002651 continue;
2652 }
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Douglas Gregor7caa6822009-07-24 20:34:43 +00002654 // Instantiate static data member definitions.
2655 VarDecl *Var = cast<VarDecl>(Inst.first);
2656 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002657
Chandler Carruth291b4412010-02-13 10:17:50 +00002658 // Don't try to instantiate declarations if the most recent redeclaration
2659 // is invalid.
2660 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2661 continue;
2662
2663 // Check if the most recent declaration has changed the specialization kind
2664 // and removed the need for implicit instantiation.
2665 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2666 case TSK_Undeclared:
2667 assert(false && "Cannot instantitiate an undeclared specialization.");
2668 case TSK_ExplicitInstantiationDeclaration:
2669 case TSK_ExplicitInstantiationDefinition:
2670 case TSK_ExplicitSpecialization:
2671 continue; // No longer need implicit instantiation.
2672 case TSK_ImplicitInstantiation:
2673 break;
2674 }
2675
Mike Stump1eb44332009-09-09 15:08:12 +00002676 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002677 Var->getLocation(), *this,
2678 Context.getSourceManager(),
2679 "instantiating static data member "
2680 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Douglas Gregor7caa6822009-07-24 20:34:43 +00002682 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002683 }
2684}
John McCall0c01d182010-03-24 05:22:00 +00002685
2686void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2687 const MultiLevelTemplateArgumentList &TemplateArgs) {
2688 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2689 E = Pattern->ddiag_end(); I != E; ++I) {
2690 DependentDiagnostic *DD = *I;
2691
2692 switch (DD->getKind()) {
2693 case DependentDiagnostic::Access:
2694 HandleDependentAccessCheck(*DD, TemplateArgs);
2695 break;
2696 }
2697 }
2698}