blob: da8480633d5b283935e42159bdc8b5ca46c7aa07 [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
1764 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1765 PartialSpec->getLocation(),
1766 InstParams,
1767 ClassTemplate,
1768 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001769 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001770 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001771 0,
1772 ClassTemplate->getPartialSpecializations().size());
John McCallb6217662010-03-15 10:12:16 +00001773 // Substitute the nested name specifier, if any.
1774 if (SubstQualifier(PartialSpec, InstPartialSpec))
1775 return 0;
1776
Douglas Gregored9c0f92009-10-29 00:04:11 +00001777 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1778 InstPartialSpec->setTypeAsWritten(WrittenTy);
1779
1780 // Add this partial specialization to the set of class template partial
1781 // specializations.
1782 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1783 InsertPos);
1784 return false;
1785}
1786
John McCall21ef0fa2010-03-11 09:03:00 +00001787TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001788TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001789 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001790 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1791 assert(OldTInfo && "substituting function without type source info");
1792 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001793 TypeSourceInfo *NewTInfo
1794 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1795 D->getTypeSpecStartLoc(),
1796 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001797 if (!NewTInfo)
1798 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001799
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001800 if (NewTInfo != OldTInfo) {
1801 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001802 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001803 if (FunctionProtoTypeLoc *OldProtoLoc
1804 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1805 TypeLoc NewTL = NewTInfo->getTypeLoc();
1806 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1807 assert(NewProtoLoc && "Missing prototype?");
1808 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1809 // FIXME: Variadic templates will break this.
1810 Params.push_back(NewProtoLoc->getArg(i));
1811 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001812 OldProtoLoc->getArg(i),
1813 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001814 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001815 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001816 } else {
1817 // The function type itself was not dependent and therefore no
1818 // substitution occurred. However, we still need to instantiate
1819 // the function parameters themselves.
1820 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001821 if (FunctionProtoTypeLoc *OldProtoLoc
1822 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1823 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1824 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1825 if (!Parm)
1826 return 0;
1827 Params.push_back(Parm);
1828 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001829 }
1830 }
John McCall21ef0fa2010-03-11 09:03:00 +00001831 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001832}
1833
Mike Stump1eb44332009-09-09 15:08:12 +00001834/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001835/// declaration (New) from the corresponding fields of its template (Tmpl).
1836///
1837/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001838bool
1839TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001840 FunctionDecl *Tmpl) {
1841 if (Tmpl->isDeleted())
1842 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Douglas Gregorcca9e962009-07-01 22:01:06 +00001844 // If we are performing substituting explicitly-specified template arguments
1845 // or deduced template arguments into a function template and we reach this
1846 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001847 // to keeping the new function template specialization. We therefore
1848 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001849 // into a template instantiation for this specific function template
1850 // specialization, which is not a SFINAE context, so that we diagnose any
1851 // further errors in the declaration itself.
1852 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1853 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1854 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1855 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001856 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001857 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001858 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001859 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001860 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001861 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1862 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001863 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001864 }
1865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001867 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1868 assert(Proto && "Function template without prototype?");
1869
1870 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1871 Proto->getNoReturnAttr()) {
1872 // The function has an exception specification or a "noreturn"
1873 // attribute. Substitute into each of the exception types.
1874 llvm::SmallVector<QualType, 4> Exceptions;
1875 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1876 // FIXME: Poor location information!
1877 QualType T
1878 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1879 New->getLocation(), New->getDeclName());
1880 if (T.isNull() ||
1881 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1882 continue;
1883
1884 Exceptions.push_back(T);
1885 }
1886
1887 // Rebuild the function type
1888
1889 const FunctionProtoType *NewProto
1890 = New->getType()->getAs<FunctionProtoType>();
1891 assert(NewProto && "Template instantiation without function prototype?");
1892 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1893 NewProto->arg_type_begin(),
1894 NewProto->getNumArgs(),
1895 NewProto->isVariadic(),
1896 NewProto->getTypeQuals(),
1897 Proto->hasExceptionSpec(),
1898 Proto->hasAnyExceptionSpec(),
1899 Exceptions.size(),
1900 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001901 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001902 }
1903
Douglas Gregore53060f2009-06-25 22:08:12 +00001904 return false;
1905}
1906
Douglas Gregor5545e162009-03-24 00:38:23 +00001907/// \brief Initializes common fields of an instantiated method
1908/// declaration (New) from the corresponding fields of its template
1909/// (Tmpl).
1910///
1911/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001912bool
1913TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001914 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001915 if (InitFunctionInstantiation(New, Tmpl))
1916 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Douglas Gregor5545e162009-03-24 00:38:23 +00001918 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1919 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001920 if (Tmpl->isVirtualAsWritten())
1921 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001922
1923 // FIXME: attributes
1924 // FIXME: New needs a pointer to Tmpl
1925 return false;
1926}
Douglas Gregora58861f2009-05-13 20:28:22 +00001927
1928/// \brief Instantiate the definition of the given function from its
1929/// template.
1930///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001931/// \param PointOfInstantiation the point at which the instantiation was
1932/// required. Note that this is not precisely a "point of instantiation"
1933/// for the function, but it's close.
1934///
Douglas Gregora58861f2009-05-13 20:28:22 +00001935/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001936/// function template specialization or member function of a class template
1937/// specialization.
1938///
1939/// \param Recursive if true, recursively instantiates any functions that
1940/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001941///
1942/// \param DefinitionRequired if true, then we are performing an explicit
1943/// instantiation where the body of the function is required. Complain if
1944/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001945void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001946 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001947 bool Recursive,
1948 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001949 if (Function->isInvalidDecl())
1950 return;
1951
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001952 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001954 // Never instantiate an explicit specialization.
1955 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1956 return;
1957
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001958 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001959 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001960 Stmt *Pattern = 0;
1961 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001962 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001963
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001964 if (!Pattern) {
1965 if (DefinitionRequired) {
1966 if (Function->getPrimaryTemplate())
1967 Diag(PointOfInstantiation,
1968 diag::err_explicit_instantiation_undefined_func_template)
1969 << Function->getPrimaryTemplate();
1970 else
1971 Diag(PointOfInstantiation,
1972 diag::err_explicit_instantiation_undefined_member)
1973 << 1 << Function->getDeclName() << Function->getDeclContext();
1974
1975 if (PatternDecl)
1976 Diag(PatternDecl->getLocation(),
1977 diag::note_explicit_instantiation_here);
1978 }
1979
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001980 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001981 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001982
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001983 // C++0x [temp.explicit]p9:
1984 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001985 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001986 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001987 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001988 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001989 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001990 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001992 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1993 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00001994 return;
1995
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001996 // If we're performing recursive template instantiation, create our own
1997 // queue of pending implicit instantiations that we will instantiate later,
1998 // while we're still within our own instantiation context.
1999 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2000 if (Recursive)
2001 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002003 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2004
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002005 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002006 // recorded, unless we're actually a member function within a local
2007 // class, in which case we need to merge our results with the parent
2008 // scope (of the enclosing function).
2009 bool MergeWithParentScope = false;
2010 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2011 MergeWithParentScope = Rec->isLocalClass();
2012
2013 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002015 // Introduce the instantiated function parameters into the local
2016 // instantiation scope.
2017 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2018 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2019 Function->getParamDecl(I));
2020
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002021 // Enter the scope of this instantiation. We don't use
2022 // PushDeclContext because we don't have a scope.
2023 DeclContext *PreviousContext = CurContext;
2024 CurContext = Function;
2025
Mike Stump1eb44332009-09-09 15:08:12 +00002026 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002027 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002028
2029 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002030 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002031 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2032 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2033 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002034 }
2035
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002036 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002037 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002038
Douglas Gregor52604ab2009-09-11 21:19:12 +00002039 if (Body.isInvalid())
2040 Function->setInvalidDecl();
2041
Mike Stump1eb44332009-09-09 15:08:12 +00002042 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002043 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002044
John McCall0c01d182010-03-24 05:22:00 +00002045 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2046
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002047 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002048
2049 DeclGroupRef DG(Function);
2050 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Douglas Gregor60406be2010-01-16 22:29:39 +00002052 // This class may have local implicit instantiations that need to be
2053 // instantiation within this scope.
2054 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2055 Scope.Exit();
2056
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002057 if (Recursive) {
2058 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002059 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002060 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002062 // Restore the set of pending implicit instantiations.
2063 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2064 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002065}
2066
2067/// \brief Instantiate the definition of the given variable from its
2068/// template.
2069///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002070/// \param PointOfInstantiation the point at which the instantiation was
2071/// required. Note that this is not precisely a "point of instantiation"
2072/// for the function, but it's close.
2073///
2074/// \param Var the already-instantiated declaration of a static member
2075/// variable of a class template specialization.
2076///
2077/// \param Recursive if true, recursively instantiates any functions that
2078/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002079///
2080/// \param DefinitionRequired if true, then we are performing an explicit
2081/// instantiation where an out-of-line definition of the member variable
2082/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002083void Sema::InstantiateStaticDataMemberDefinition(
2084 SourceLocation PointOfInstantiation,
2085 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002086 bool Recursive,
2087 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002088 if (Var->isInvalidDecl())
2089 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor7caa6822009-07-24 20:34:43 +00002091 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002092 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002093 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002094 assert(Def->isStaticDataMember() && "Not a static data member?");
2095 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Douglas Gregor0d035142009-10-27 18:42:08 +00002097 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002098 // We did not find an out-of-line definition of this static data member,
2099 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002100 // instantiate this definition (or provide a specialization for it) in
2101 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002102 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002103 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002104 Diag(PointOfInstantiation,
2105 diag::err_explicit_instantiation_undefined_member)
2106 << 2 << Var->getDeclName() << Var->getDeclContext();
2107 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2108 }
2109
Douglas Gregor7caa6822009-07-24 20:34:43 +00002110 return;
2111 }
2112
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002113 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002114 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002115 return;
2116
2117 // C++0x [temp.explicit]p9:
2118 // Except for inline functions, other explicit instantiation declarations
2119 // have the effect of suppressing the implicit instantiation of the entity
2120 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002121 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002122 == TSK_ExplicitInstantiationDeclaration)
2123 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Douglas Gregor7caa6822009-07-24 20:34:43 +00002125 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2126 if (Inst)
2127 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Douglas Gregor7caa6822009-07-24 20:34:43 +00002129 // If we're performing recursive template instantiation, create our own
2130 // queue of pending implicit instantiations that we will instantiate later,
2131 // while we're still within our own instantiation context.
2132 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2133 if (Recursive)
2134 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Douglas Gregor7caa6822009-07-24 20:34:43 +00002136 // Enter the scope of this instantiation. We don't use
2137 // PushDeclContext because we don't have a scope.
2138 DeclContext *PreviousContext = CurContext;
2139 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002141 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002142 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002143 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002144 CurContext = PreviousContext;
2145
2146 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002147 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2148 assert(MSInfo && "Missing member specialization information?");
2149 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2150 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002151 DeclGroupRef DG(Var);
2152 Consumer.HandleTopLevelDecl(DG);
2153 }
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Douglas Gregor7caa6822009-07-24 20:34:43 +00002155 if (Recursive) {
2156 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002157 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002158 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Douglas Gregor7caa6822009-07-24 20:34:43 +00002160 // Restore the set of pending implicit instantiations.
2161 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002162 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002163}
Douglas Gregor815215d2009-05-27 05:35:12 +00002164
Anders Carlsson09025312009-08-29 05:16:22 +00002165void
2166Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2167 const CXXConstructorDecl *Tmpl,
2168 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Anders Carlsson09025312009-08-29 05:16:22 +00002170 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002171 bool AnyErrors = false;
2172
Anders Carlsson09025312009-08-29 05:16:22 +00002173 // Instantiate all the initializers.
2174 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002175 InitsEnd = Tmpl->init_end();
2176 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002177 CXXBaseOrMemberInitializer *Init = *Inits;
2178
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002179 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002180 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002181 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002183 // Instantiate the initializer.
2184 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2185 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2186 AnyErrors = true;
2187 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002188 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002189
Anders Carlsson09025312009-08-29 05:16:22 +00002190 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002191 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002192 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002193 TemplateArgs,
2194 Init->getSourceLocation(),
2195 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002196 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002197 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002198 New->setInvalidDecl();
2199 continue;
2200 }
2201
John McCalla93c9342009-12-07 02:54:59 +00002202 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002203 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002204 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002205 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002206 Init->getRParenLoc(),
2207 New->getParent());
2208 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002209 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002211 // Is this an anonymous union?
2212 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002213 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2214 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002215 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002216 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2217 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002218 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002219
2220 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002221 NewArgs.size(),
2222 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002223 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002224 Init->getRParenLoc());
2225 }
2226
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002227 if (NewInit.isInvalid()) {
2228 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002229 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002230 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002231 // FIXME: It would be nice if ASTOwningVector had a release function.
2232 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Anders Carlsson09025312009-08-29 05:16:22 +00002234 NewInits.push_back((MemInitTy *)NewInit.get());
2235 }
2236 }
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Anders Carlsson09025312009-08-29 05:16:22 +00002238 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002239 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002240 /*FIXME: ColonLoc */
2241 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002242 NewInits.data(), NewInits.size(),
2243 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002244}
2245
John McCall52a575a2009-08-29 08:11:13 +00002246// TODO: this could be templated if the various decl types used the
2247// same method name.
2248static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2249 ClassTemplateDecl *Instance) {
2250 Pattern = Pattern->getCanonicalDecl();
2251
2252 do {
2253 Instance = Instance->getCanonicalDecl();
2254 if (Pattern == Instance) return true;
2255 Instance = Instance->getInstantiatedFromMemberTemplate();
2256 } while (Instance);
2257
2258 return false;
2259}
2260
Douglas Gregor0d696532009-09-28 06:34:35 +00002261static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2262 FunctionTemplateDecl *Instance) {
2263 Pattern = Pattern->getCanonicalDecl();
2264
2265 do {
2266 Instance = Instance->getCanonicalDecl();
2267 if (Pattern == Instance) return true;
2268 Instance = Instance->getInstantiatedFromMemberTemplate();
2269 } while (Instance);
2270
2271 return false;
2272}
2273
Douglas Gregored9c0f92009-10-29 00:04:11 +00002274static bool
2275isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2276 ClassTemplatePartialSpecializationDecl *Instance) {
2277 Pattern
2278 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2279 do {
2280 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2281 Instance->getCanonicalDecl());
2282 if (Pattern == Instance)
2283 return true;
2284 Instance = Instance->getInstantiatedFromMember();
2285 } while (Instance);
2286
2287 return false;
2288}
2289
John McCall52a575a2009-08-29 08:11:13 +00002290static bool isInstantiationOf(CXXRecordDecl *Pattern,
2291 CXXRecordDecl *Instance) {
2292 Pattern = Pattern->getCanonicalDecl();
2293
2294 do {
2295 Instance = Instance->getCanonicalDecl();
2296 if (Pattern == Instance) return true;
2297 Instance = Instance->getInstantiatedFromMemberClass();
2298 } while (Instance);
2299
2300 return false;
2301}
2302
2303static bool isInstantiationOf(FunctionDecl *Pattern,
2304 FunctionDecl *Instance) {
2305 Pattern = Pattern->getCanonicalDecl();
2306
2307 do {
2308 Instance = Instance->getCanonicalDecl();
2309 if (Pattern == Instance) return true;
2310 Instance = Instance->getInstantiatedFromMemberFunction();
2311 } while (Instance);
2312
2313 return false;
2314}
2315
2316static bool isInstantiationOf(EnumDecl *Pattern,
2317 EnumDecl *Instance) {
2318 Pattern = Pattern->getCanonicalDecl();
2319
2320 do {
2321 Instance = Instance->getCanonicalDecl();
2322 if (Pattern == Instance) return true;
2323 Instance = Instance->getInstantiatedFromMemberEnum();
2324 } while (Instance);
2325
2326 return false;
2327}
2328
John McCalled976492009-12-04 22:46:56 +00002329static bool isInstantiationOf(UsingShadowDecl *Pattern,
2330 UsingShadowDecl *Instance,
2331 ASTContext &C) {
2332 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2333}
2334
2335static bool isInstantiationOf(UsingDecl *Pattern,
2336 UsingDecl *Instance,
2337 ASTContext &C) {
2338 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2339}
2340
John McCall7ba107a2009-11-18 02:36:19 +00002341static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2342 UsingDecl *Instance,
2343 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002344 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002345}
2346
2347static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002348 UsingDecl *Instance,
2349 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002350 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002351}
2352
John McCall52a575a2009-08-29 08:11:13 +00002353static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2354 VarDecl *Instance) {
2355 assert(Instance->isStaticDataMember());
2356
2357 Pattern = Pattern->getCanonicalDecl();
2358
2359 do {
2360 Instance = Instance->getCanonicalDecl();
2361 if (Pattern == Instance) return true;
2362 Instance = Instance->getInstantiatedFromStaticDataMember();
2363 } while (Instance);
2364
2365 return false;
2366}
2367
John McCalled976492009-12-04 22:46:56 +00002368// Other is the prospective instantiation
2369// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002370static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002371 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002372 if (UnresolvedUsingTypenameDecl *UUD
2373 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2374 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2375 return isInstantiationOf(UUD, UD, Ctx);
2376 }
2377 }
2378
2379 if (UnresolvedUsingValueDecl *UUD
2380 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002381 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2382 return isInstantiationOf(UUD, UD, Ctx);
2383 }
2384 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002385
Anders Carlsson0d8df782009-08-29 19:37:28 +00002386 return false;
2387 }
Mike Stump1eb44332009-09-09 15:08:12 +00002388
John McCall52a575a2009-08-29 08:11:13 +00002389 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2390 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002391
John McCall52a575a2009-08-29 08:11:13 +00002392 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2393 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002394
John McCall52a575a2009-08-29 08:11:13 +00002395 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2396 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002397
Douglas Gregor7caa6822009-07-24 20:34:43 +00002398 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002399 if (Var->isStaticDataMember())
2400 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2401
2402 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2403 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002404
Douglas Gregor0d696532009-09-28 06:34:35 +00002405 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2406 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2407
Douglas Gregored9c0f92009-10-29 00:04:11 +00002408 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2409 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2410 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2411 PartialSpec);
2412
Anders Carlssond8b285f2009-09-01 04:26:58 +00002413 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2414 if (!Field->getDeclName()) {
2415 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002416 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002417 cast<FieldDecl>(D);
2418 }
2419 }
Mike Stump1eb44332009-09-09 15:08:12 +00002420
John McCalled976492009-12-04 22:46:56 +00002421 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2422 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2423
2424 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2425 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2426
Douglas Gregor815215d2009-05-27 05:35:12 +00002427 return D->getDeclName() && isa<NamedDecl>(Other) &&
2428 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2429}
2430
2431template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002432static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002433 NamedDecl *D,
2434 ForwardIterator first,
2435 ForwardIterator last) {
2436 for (; first != last; ++first)
2437 if (isInstantiationOf(Ctx, D, *first))
2438 return cast<NamedDecl>(*first);
2439
2440 return 0;
2441}
2442
John McCall02cace72009-08-28 07:59:38 +00002443/// \brief Finds the instantiation of the given declaration context
2444/// within the current instantiation.
2445///
2446/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002447DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002448 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002449 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002450 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002451 return cast_or_null<DeclContext>(ID);
2452 } else return DC;
2453}
2454
Douglas Gregored961e72009-05-27 17:54:46 +00002455/// \brief Find the instantiation of the given declaration within the
2456/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002457///
2458/// This routine is intended to be used when \p D is a declaration
2459/// referenced from within a template, that needs to mapped into the
2460/// corresponding declaration within an instantiation. For example,
2461/// given:
2462///
2463/// \code
2464/// template<typename T>
2465/// struct X {
2466/// enum Kind {
2467/// KnownValue = sizeof(T)
2468/// };
2469///
2470/// bool getKind() const { return KnownValue; }
2471/// };
2472///
2473/// template struct X<int>;
2474/// \endcode
2475///
2476/// In the instantiation of X<int>::getKind(), we need to map the
2477/// EnumConstantDecl for KnownValue (which refers to
2478/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002479/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2480/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002481NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002482 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002483 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002484 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002485 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002486 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002487 // D is a local of some kind. Look into the map of local
2488 // declarations to their instantiations.
2489 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2490 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002491
Douglas Gregore95b4092009-09-16 18:34:49 +00002492 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2493 if (!Record->isDependentContext())
2494 return D;
2495
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002496 // If the RecordDecl is actually the injected-class-name or a
2497 // "templated" declaration for a class template, class template
2498 // partial specialization, or a member class of a class template,
2499 // substitute into the injected-class-name of the class template
2500 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002501 QualType T;
2502 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2503
2504 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002505 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002506 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2507 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002508 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002509
2510 // If we call SubstType with an InjectedClassNameType here we
2511 // can end up in an infinite loop.
2512 T = Context.getTypeDeclType(Record);
2513 assert(isa<InjectedClassNameType>(T) &&
2514 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002515 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002516 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002517
2518 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002519 // Substitute into the injected-class-name to get the type
2520 // corresponding to the instantiation we want, which may also be
2521 // the current instantiation (if we're in a template
2522 // definition). This substitution should never fail, since we
2523 // know we can instantiate the injected-class-name or we
2524 // wouldn't have gotten to the injected-class-name!
2525
2526 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2527 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002528 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2529 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2530
2531 if (!T->isDependentType()) {
2532 assert(T->isRecordType() && "Instantiation must produce a record type");
2533 return T->getAs<RecordType>()->getDecl();
2534 }
2535
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002536 // We are performing "partial" template instantiation to create
2537 // the member declarations for the members of a class template
2538 // specialization. Therefore, D is actually referring to something
2539 // in the current instantiation. Look through the current
2540 // context, which contains actual instantiations, to find the
2541 // instantiation of the "current instantiation" that D refers
2542 // to.
2543 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002544 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002545 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002546 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002547 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002548 if (isInstantiationOf(ClassTemplate,
2549 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002550 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002551
2552 if (!DC->isDependentContext())
2553 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002554 }
2555
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002556 // We're performing "instantiation" of a member of the current
2557 // instantiation while we are type-checking the
2558 // definition. Compute the declaration context and return that.
2559 assert(!SawNonDependentContext &&
2560 "No dependent context while instantiating record");
2561 DeclContext *DC = computeDeclContext(T);
2562 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002563 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002564 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002565 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002566
Douglas Gregore95b4092009-09-16 18:34:49 +00002567 // Fall through to deal with other dependent record types (e.g.,
2568 // anonymous unions in class templates).
2569 }
John McCall52a575a2009-08-29 08:11:13 +00002570
Douglas Gregore95b4092009-09-16 18:34:49 +00002571 if (!ParentDC->isDependentContext())
2572 return D;
2573
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002574 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002575 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002576 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Douglas Gregor815215d2009-05-27 05:35:12 +00002578 if (ParentDC != D->getDeclContext()) {
2579 // We performed some kind of instantiation in the parent context,
2580 // so now we need to look into the instantiated parent context to
2581 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002582
John McCall3cb0ebd2010-03-10 03:28:59 +00002583 // If our context used to be dependent, we may need to instantiate
2584 // it before performing lookup into that context.
2585 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002586 if (!Spec->isDependentContext()) {
2587 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002588 const RecordType *Tag = T->getAs<RecordType>();
2589 assert(Tag && "type of non-dependent record is not a RecordType");
2590 if (!Tag->isBeingDefined() &&
2591 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2592 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002593 }
2594 }
2595
Douglas Gregor815215d2009-05-27 05:35:12 +00002596 NamedDecl *Result = 0;
2597 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002598 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002599 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2600 } else {
2601 // Since we don't have a name for the entity we're looking for,
2602 // our only option is to walk through all of the declarations to
2603 // find that name. This will occur in a few cases:
2604 //
2605 // - anonymous struct/union within a template
2606 // - unnamed class/struct/union/enum within a template
2607 //
2608 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002609 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002610 ParentDC->decls_begin(),
2611 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002612 }
Mike Stump1eb44332009-09-09 15:08:12 +00002613
John McCall9f54ad42009-12-10 09:41:52 +00002614 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002615 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2616 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002617 && "Unable to find instantiation of declaration!");
2618
Douglas Gregor815215d2009-05-27 05:35:12 +00002619 D = Result;
2620 }
2621
Douglas Gregor815215d2009-05-27 05:35:12 +00002622 return D;
2623}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002624
Mike Stump1eb44332009-09-09 15:08:12 +00002625/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002626/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002627void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2628 while (!PendingLocalImplicitInstantiations.empty() ||
2629 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2630 PendingImplicitInstantiation Inst;
2631
2632 if (PendingLocalImplicitInstantiations.empty()) {
2633 Inst = PendingImplicitInstantiations.front();
2634 PendingImplicitInstantiations.pop_front();
2635 } else {
2636 Inst = PendingLocalImplicitInstantiations.front();
2637 PendingLocalImplicitInstantiations.pop_front();
2638 }
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Douglas Gregor7caa6822009-07-24 20:34:43 +00002640 // Instantiate function definitions
2641 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002642 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002643 Function->getLocation(), *this,
2644 Context.getSourceManager(),
2645 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002647 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002648 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002649 continue;
2650 }
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Douglas Gregor7caa6822009-07-24 20:34:43 +00002652 // Instantiate static data member definitions.
2653 VarDecl *Var = cast<VarDecl>(Inst.first);
2654 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002655
Chandler Carruth291b4412010-02-13 10:17:50 +00002656 // Don't try to instantiate declarations if the most recent redeclaration
2657 // is invalid.
2658 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2659 continue;
2660
2661 // Check if the most recent declaration has changed the specialization kind
2662 // and removed the need for implicit instantiation.
2663 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2664 case TSK_Undeclared:
2665 assert(false && "Cannot instantitiate an undeclared specialization.");
2666 case TSK_ExplicitInstantiationDeclaration:
2667 case TSK_ExplicitInstantiationDefinition:
2668 case TSK_ExplicitSpecialization:
2669 continue; // No longer need implicit instantiation.
2670 case TSK_ImplicitInstantiation:
2671 break;
2672 }
2673
Mike Stump1eb44332009-09-09 15:08:12 +00002674 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002675 Var->getLocation(), *this,
2676 Context.getSourceManager(),
2677 "instantiating static data member "
2678 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregor7caa6822009-07-24 20:34:43 +00002680 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002681 }
2682}
John McCall0c01d182010-03-24 05:22:00 +00002683
2684void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2685 const MultiLevelTemplateArgumentList &TemplateArgs) {
2686 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2687 E = Pattern->ddiag_end(); I != E; ++I) {
2688 DependentDiagnostic *DD = *I;
2689
2690 switch (DD->getKind()) {
2691 case DependentDiagnostic::Access:
2692 HandleDependentAccessCheck(*DD, TemplateArgs);
2693 break;
2694 }
2695 }
2696}