blob: 6fc95634ab7d61cb3f8b9937e90cdb6ebf08197d [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//===----------------------------------------------------------------------===/
Douglas Gregore737f502010-08-12 20:07:10 +000012#include "clang/Sema/Sema.h"
13#include "clang/Sema/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
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
35 typedef Sema::OwningExprResult OwningExprResult;
36
37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000038 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000039 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000040
Mike Stump390b4cc2009-05-16 07:39:55 +000041 // FIXME: Once we get closer to completion, replace these manually-written
42 // declarations with automatically-generated ones from
Sean Hunt9a555912010-05-30 07:21:58 +000043 // clang/AST/DeclNodes.inc.
Douglas Gregor4f722be2009-03-25 15:45:12 +000044 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000046 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000048 Decl *VisitVarDecl(VarDecl *D);
Abramo Bagnara6206d532010-06-05 05:09:32 +000049 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000050 Decl *VisitFieldDecl(FieldDecl *D);
51 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
52 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000053 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000054 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000055 Decl *VisitFunctionDecl(FunctionDecl *D,
56 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000057 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000058 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
59 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000060 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000061 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000062 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000063 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000064 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000065 Decl *VisitClassTemplatePartialSpecializationDecl(
66 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000067 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000068 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000069 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000070 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000071 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000072 Decl *VisitUsingDecl(UsingDecl *D);
73 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000074 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
75 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Douglas Gregor8dbc2692009-03-17 21:15:40 +000077 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000078 Decl *VisitDecl(Decl *D) {
79 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
80 Diagnostic::Error,
81 "cannot instantiate %0 yet");
82 SemaRef.Diag(D->getLocation(), DiagID)
83 << D->getDeclKindName();
84
Douglas Gregor8dbc2692009-03-17 21:15:40 +000085 return 0;
86 }
Douglas Gregor5545e162009-03-24 00:38:23 +000087
88 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000089 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000090 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000091 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000092 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000093
94 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000095 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +000096
97 bool SubstQualifier(const DeclaratorDecl *OldDecl,
98 DeclaratorDecl *NewDecl);
99 bool SubstQualifier(const TagDecl *OldDecl,
100 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000101
102 bool InstantiateClassTemplatePartialSpecialization(
103 ClassTemplateDecl *ClassTemplate,
104 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000105 };
106}
107
John McCallb6217662010-03-15 10:12:16 +0000108bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
109 DeclaratorDecl *NewDecl) {
110 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
111 if (!OldQual) return false;
112
113 SourceRange QualRange = OldDecl->getQualifierRange();
114
115 NestedNameSpecifier *NewQual
116 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
117 if (!NewQual)
118 return true;
119
120 NewDecl->setQualifierInfo(NewQual, QualRange);
121 return false;
122}
123
124bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
125 TagDecl *NewDecl) {
126 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
127 if (!OldQual) return false;
128
129 SourceRange QualRange = OldDecl->getQualifierRange();
130
131 NestedNameSpecifier *NewQual
132 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
133 if (!NewQual)
134 return true;
135
136 NewDecl->setQualifierInfo(NewQual, QualRange);
137 return false;
138}
139
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000140// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +0000141void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
142 Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +0000143 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
144 i != e; ++i) {
145 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000146 // FIXME: This should be generalized to more than just the AlignedAttr.
147 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +0000148 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000149 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +0000150 EnterExpressionEvaluationContext Unevaluated(*this,
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000151 Action::Unevaluated);
152
Sean Huntcf807c42010-08-18 23:23:40 +0000153 if (Aligned->isAlignmentExpr()) {
154 OwningExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
155 TemplateArgs);
156 if (!Result.isInvalid())
157 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
158 }
159 else {
160 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
161 TemplateArgs,
162 Aligned->getLocation(),
163 DeclarationName());
164 if (Result)
165 AddAlignedAttr(Aligned->getLocation(), New, Result);
166 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000167 continue;
168 }
169 }
170
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000171 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +0000172 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000173 New->addAttr(NewAttr);
174 }
175}
176
Douglas Gregor4f722be2009-03-25 15:45:12 +0000177Decl *
178TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
179 assert(false && "Translation units cannot be instantiated");
180 return D;
181}
182
183Decl *
184TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
185 assert(false && "Namespaces cannot be instantiated");
186 return D;
187}
188
John McCall3dbd3d52010-02-16 06:53:13 +0000189Decl *
190TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
191 NamespaceAliasDecl *Inst
192 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
193 D->getNamespaceLoc(),
194 D->getAliasLoc(),
195 D->getNamespace()->getIdentifier(),
196 D->getQualifierRange(),
197 D->getQualifier(),
198 D->getTargetNameLoc(),
199 D->getNamespace());
200 Owner->addDecl(Inst);
201 return Inst;
202}
203
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000204Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
205 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000206 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000207 if (DI->getType()->isDependentType() ||
208 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000209 DI = SemaRef.SubstType(DI, TemplateArgs,
210 D->getLocation(), D->getDeclName());
211 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000212 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000213 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000214 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000215 } else {
216 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000217 }
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000219 // Create the new typedef
220 TypedefDecl *Typedef
221 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000222 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000223 if (Invalid)
224 Typedef->setInvalidDecl();
225
Douglas Gregord57a38e2010-04-23 16:25:07 +0000226 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
227 TagDecl *TD = TT->getDecl();
228
229 // If the TagDecl that the TypedefDecl points to is an anonymous decl
230 // keep track of the TypedefDecl.
231 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
232 TD->setTypedefForAnonDecl(Typedef);
233 }
234
John McCall5126fd02009-12-30 00:31:22 +0000235 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000236 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
237 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000238 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
239 }
240
John McCall1d8d1cc2010-08-01 02:01:53 +0000241 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000242
John McCall46460a62010-01-20 21:53:11 +0000243 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000244 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000246 return Typedef;
247}
248
Douglas Gregor6eef5192009-12-14 19:27:10 +0000249/// \brief Instantiate the arguments provided as part of initialization.
250///
251/// \returns true if an error occurred, false otherwise.
252static bool InstantiateInitializationArguments(Sema &SemaRef,
253 Expr **Args, unsigned NumArgs,
254 const MultiLevelTemplateArgumentList &TemplateArgs,
255 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
256 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
257 for (unsigned I = 0; I != NumArgs; ++I) {
258 // When we hit the first defaulted argument, break out of the loop:
259 // we don't pass those default arguments on.
260 if (Args[I]->isDefaultArgument())
261 break;
262
263 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
264 if (Arg.isInvalid())
265 return true;
266
267 Expr *ArgExpr = (Expr *)Arg.get();
268 InitArgs.push_back(Arg.release());
269
270 // FIXME: We're faking all of the comma locations. Do we need them?
271 FakeCommaLocs.push_back(
272 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
273 }
274
275 return false;
276}
277
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000278/// \brief Instantiate an initializer, breaking it into separate
279/// initialization arguments.
280///
281/// \param S The semantic analysis object.
282///
283/// \param Init The initializer to instantiate.
284///
285/// \param TemplateArgs Template arguments to be substituted into the
286/// initializer.
287///
288/// \param NewArgs Will be filled in with the instantiation arguments.
289///
290/// \returns true if an error occurred, false otherwise
291static bool InstantiateInitializer(Sema &S, Expr *Init,
292 const MultiLevelTemplateArgumentList &TemplateArgs,
293 SourceLocation &LParenLoc,
294 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
295 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
296 SourceLocation &RParenLoc) {
297 NewArgs.clear();
298 LParenLoc = SourceLocation();
299 RParenLoc = SourceLocation();
300
301 if (!Init)
302 return false;
303
304 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
305 Init = ExprTemp->getSubExpr();
306
307 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
308 Init = Binder->getSubExpr();
309
310 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
311 Init = ICE->getSubExprAsWritten();
312
313 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
314 LParenLoc = ParenList->getLParenLoc();
315 RParenLoc = ParenList->getRParenLoc();
316 return InstantiateInitializationArguments(S, ParenList->getExprs(),
317 ParenList->getNumExprs(),
318 TemplateArgs, CommaLocs,
319 NewArgs);
320 }
321
322 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000323 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
324 if (InstantiateInitializationArguments(S,
325 Construct->getArgs(),
326 Construct->getNumArgs(),
327 TemplateArgs,
328 CommaLocs, NewArgs))
329 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000330
Douglas Gregor28329e52010-03-24 21:22:47 +0000331 // FIXME: Fake locations!
332 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
333 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
334 return false;
335 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000336 }
337
338 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
339 if (Result.isInvalid())
340 return true;
341
342 NewArgs.push_back(Result.takeAs<Expr>());
343 return false;
344}
345
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000346Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000347 // If this is the variable for an anonymous struct or union,
348 // instantiate the anonymous struct/union type first.
349 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
350 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
351 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
352 return 0;
353
John McCallce3ff2b2009-08-25 22:02:44 +0000354 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000355 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000356 TemplateArgs,
357 D->getTypeSpecStartLoc(),
358 D->getDeclName());
359 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000360 return 0;
361
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000362 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000363 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
364 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000365 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000366 D->getStorageClass(),
367 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000368 Var->setThreadSpecified(D->isThreadSpecified());
369 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000370
John McCallb6217662010-03-15 10:12:16 +0000371 // Substitute the nested name specifier, if any.
372 if (SubstQualifier(D, Var))
373 return 0;
374
Mike Stump1eb44332009-09-09 15:08:12 +0000375 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000376 // out-of-line, the instantiation will have the same lexical
377 // context (which will be a namespace scope) as the template.
378 if (D->isOutOfLine())
379 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000380
John McCall46460a62010-01-20 21:53:11 +0000381 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000382
383 if (!D->isStaticDataMember())
384 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000385
Mike Stump390b4cc2009-05-16 07:39:55 +0000386 // FIXME: In theory, we could have a previous declaration for variables that
387 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000388 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000389 // FIXME: having to fake up a LookupResult is dumb.
390 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000391 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000392 if (D->isStaticDataMember())
393 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000394 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Douglas Gregor7caa6822009-07-24 20:34:43 +0000396 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000397 if (!D->isStaticDataMember())
398 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000399 Owner->makeDeclVisibleInContext(Var);
400 } else {
401 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000402 if (Owner->isFunctionOrMethod())
403 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000404 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000405 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000406
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000407 // Link instantiations of static data members back to the template from
408 // which they were instantiated.
409 if (Var->isStaticDataMember())
410 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000411 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000412
Douglas Gregor60c93c92010-02-09 07:26:29 +0000413 if (Var->getAnyInitializer()) {
414 // We already have an initializer in the class.
415 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000416 if (Var->isStaticDataMember() && !D->isOutOfLine())
417 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
418 else
419 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
420
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000421 // Instantiate the initializer.
422 SourceLocation LParenLoc, RParenLoc;
423 llvm::SmallVector<SourceLocation, 4> CommaLocs;
424 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
425 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
426 CommaLocs, InitArgs, RParenLoc)) {
427 // Attach the initializer to the declaration.
428 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000429 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000430 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000431 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000432 move_arg(InitArgs),
433 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000434 RParenLoc);
435 } else if (InitArgs.size() == 1) {
436 Expr *Init = (Expr*)(InitArgs.take()[0]);
437 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
438 SemaRef.Owned(Init),
439 false);
440 } else {
441 assert(InitArgs.size() == 0);
442 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000443 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000444 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000445 // FIXME: Not too happy about invalidating the declaration
446 // because of a bogus initializer.
447 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000448 }
449
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000450 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000451 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
452 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000453
Douglas Gregor5764f612010-05-08 23:05:03 +0000454 // Diagnose unused local variables.
455 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
456 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000457
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000458 return Var;
459}
460
Abramo Bagnara6206d532010-06-05 05:09:32 +0000461Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
462 AccessSpecDecl* AD
463 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
464 D->getAccessSpecifierLoc(), D->getColonLoc());
465 Owner->addHiddenDecl(AD);
466 return AD;
467}
468
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000469Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
470 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000471 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000472 if (DI->getType()->isDependentType() ||
473 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000474 DI = SemaRef.SubstType(DI, TemplateArgs,
475 D->getLocation(), D->getDeclName());
476 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000477 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000478 Invalid = true;
479 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000480 // C++ [temp.arg.type]p3:
481 // If a declaration acquires a function type through a type
482 // dependent on a template-parameter and this causes a
483 // declaration that does not use the syntactic form of a
484 // function declarator to have function type, the program is
485 // ill-formed.
486 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000487 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000488 Invalid = true;
489 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000490 } else {
491 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000492 }
493
494 Expr *BitWidth = D->getBitWidth();
495 if (Invalid)
496 BitWidth = 0;
497 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000498 // The bit-width expression is not potentially evaluated.
499 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000501 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000502 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000503 if (InstantiatedBitWidth.isInvalid()) {
504 Invalid = true;
505 BitWidth = 0;
506 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000507 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000508 }
509
John McCall07fb6be2009-10-22 23:33:21 +0000510 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
511 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000512 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000513 D->getLocation(),
514 D->isMutable(),
515 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000516 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000517 D->getAccess(),
518 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000519 if (!Field) {
520 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000521 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000522 }
Mike Stump1eb44332009-09-09 15:08:12 +0000523
John McCall1d8d1cc2010-08-01 02:01:53 +0000524 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000525
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000526 if (Invalid)
527 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000529 if (!Field->getDeclName()) {
530 // Keep track of where this decl came from.
531 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000532 }
533 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
534 if (Parent->isAnonymousStructOrUnion() &&
535 Parent->getLookupContext()->isFunctionOrMethod())
536 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000539 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000540 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000541 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000542
543 return Field;
544}
545
John McCall02cace72009-08-28 07:59:38 +0000546Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000547 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000548 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000549 if (TypeSourceInfo *Ty = D->getFriendType()) {
550 TypeSourceInfo *InstTy =
551 SemaRef.SubstType(Ty, TemplateArgs,
552 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000553 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000554 return 0;
John McCall02cace72009-08-28 07:59:38 +0000555
Douglas Gregor06245bf2010-04-07 17:57:12 +0000556 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
557 if (!FD)
558 return 0;
559
560 FD->setAccess(AS_public);
561 Owner->addDecl(FD);
562 return FD;
563 }
564
565 NamedDecl *ND = D->getFriendDecl();
566 assert(ND && "friend decl must be a decl or a type!");
567
John McCallaf2094e2010-04-08 09:05:18 +0000568 // All of the Visit implementations for the various potential friend
569 // declarations have to be carefully written to work for friend
570 // objects, with the most important detail being that the target
571 // decl should almost certainly not be placed in Owner.
572 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000573 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
John McCall02cace72009-08-28 07:59:38 +0000575 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000576 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
577 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000578 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000579 Owner->addDecl(FD);
580 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000581}
582
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000583Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
584 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Douglas Gregorac7610d2009-06-22 20:57:11 +0000586 // The expression in a static assertion is not potentially evaluated.
587 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000589 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000590 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000591 if (InstantiatedAssertExpr.isInvalid())
592 return 0;
593
Douglas Gregor43d9d922009-08-08 01:41:12 +0000594 OwningExprResult Message(SemaRef, D->getMessage());
595 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000596 Decl *StaticAssert
597 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000598 move(InstantiatedAssertExpr),
599 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000600 return StaticAssert;
601}
602
603Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000604 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000606 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000607 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000608 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000609 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000610 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000611 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000612 Enum->startDefinition();
613
Douglas Gregor96084f12010-03-01 19:00:07 +0000614 if (D->getDeclContext()->isFunctionOrMethod())
615 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
616
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000617 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000618
619 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000620 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
621 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000622 EC != ECEnd; ++EC) {
623 // The specified value for the enumerator.
624 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000625 if (Expr *UninstValue = EC->getInitExpr()) {
626 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000627 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000628 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000629
John McCallce3ff2b2009-08-25 22:02:44 +0000630 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000631 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000632
633 // Drop the initial value and continue.
634 bool isInvalid = false;
635 if (Value.isInvalid()) {
636 Value = SemaRef.Owned((Expr *)0);
637 isInvalid = true;
638 }
639
Mike Stump1eb44332009-09-09 15:08:12 +0000640 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000641 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
642 EC->getLocation(), EC->getIdentifier(),
643 move(Value));
644
645 if (isInvalid) {
646 if (EnumConst)
647 EnumConst->setInvalidDecl();
648 Enum->setInvalidDecl();
649 }
650
651 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000652 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000653 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000654 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000655 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000656
657 if (D->getDeclContext()->isFunctionOrMethod()) {
658 // If the enumeration is within a function or method, record the enum
659 // constant as a local.
660 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
661 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000662 }
663 }
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000665 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000666 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000667 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
668 Sema::DeclPtrTy::make(Enum),
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000669 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000670 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000671
672 return Enum;
673}
674
Douglas Gregor6477b692009-03-25 15:04:13 +0000675Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
676 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
677 return 0;
678}
679
John McCalle29ba202009-08-20 01:44:21 +0000680Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000681 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
682
Douglas Gregor550d9b22009-10-31 17:21:17 +0000683 // Create a local instantiation scope for this class template, which
684 // will contain the instantiations of the template parameters.
685 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000686 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000687 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000688 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000689 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000690
691 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000692
693 // Instantiate the qualifier. We have to do this first in case
694 // we're a friend declaration, because if we are then we need to put
695 // the new declaration in the appropriate context.
696 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
697 if (Qualifier) {
698 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
699 Pattern->getQualifierRange(),
700 TemplateArgs);
701 if (!Qualifier) return 0;
702 }
703
704 CXXRecordDecl *PrevDecl = 0;
705 ClassTemplateDecl *PrevClassTemplate = 0;
706
707 // If this isn't a friend, then it's a member template, in which
708 // case we just want to build the instantiation in the
709 // specialization. If it is a friend, we want to build it in
710 // the appropriate context.
711 DeclContext *DC = Owner;
712 if (isFriend) {
713 if (Qualifier) {
714 CXXScopeSpec SS;
715 SS.setScopeRep(Qualifier);
716 SS.setRange(Pattern->getQualifierRange());
717 DC = SemaRef.computeDeclContext(SS);
718 if (!DC) return 0;
719 } else {
720 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
721 Pattern->getDeclContext(),
722 TemplateArgs);
723 }
724
725 // Look for a previous declaration of the template in the owning
726 // context.
727 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
728 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
729 SemaRef.LookupQualifiedName(R, DC);
730
731 if (R.isSingleResult()) {
732 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
733 if (PrevClassTemplate)
734 PrevDecl = PrevClassTemplate->getTemplatedDecl();
735 }
736
737 if (!PrevClassTemplate && Qualifier) {
738 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000739 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
740 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000741 return 0;
742 }
743
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000744 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000745 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000746 bool Complain = true;
747
748 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
749 // template for struct std::tr1::__detail::_Map_base, where the
750 // template parameters of the friend declaration don't match the
751 // template parameters of the original declaration. In this one
752 // case, we don't complain about the ill-formed friend
753 // declaration.
754 if (isFriend && Pattern->getIdentifier() &&
755 Pattern->getIdentifier()->isStr("_Map_base") &&
756 DC->isNamespace() &&
757 cast<NamespaceDecl>(DC)->getIdentifier() &&
758 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
759 DeclContext *DCParent = DC->getParent();
760 if (DCParent->isNamespace() &&
761 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
762 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
763 DeclContext *DCParent2 = DCParent->getParent();
764 if (DCParent2->isNamespace() &&
765 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
766 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
767 DCParent2->getParent()->isTranslationUnit())
768 Complain = false;
769 }
770 }
771
John McCall93ba8572010-03-25 06:39:04 +0000772 TemplateParameterList *PrevParams
773 = PrevClassTemplate->getTemplateParameters();
774
775 // Make sure the parameter lists match.
776 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000777 Complain,
778 Sema::TPL_TemplateMatch)) {
779 if (Complain)
780 return 0;
781
782 AdoptedPreviousTemplateParams = true;
783 InstParams = PrevParams;
784 }
John McCall93ba8572010-03-25 06:39:04 +0000785
786 // Do some additional validation, then merge default arguments
787 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000788 if (!AdoptedPreviousTemplateParams &&
789 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000790 Sema::TPC_ClassTemplate))
791 return 0;
792 }
793 }
794
John McCalle29ba202009-08-20 01:44:21 +0000795 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000796 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000797 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000798 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000799 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000800
John McCall93ba8572010-03-25 06:39:04 +0000801 if (Qualifier)
802 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000803
John McCalle29ba202009-08-20 01:44:21 +0000804 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000805 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
806 D->getIdentifier(), InstParams, RecordInst,
807 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000808 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000809
John McCall93ba8572010-03-25 06:39:04 +0000810 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000811 if (PrevClassTemplate)
812 Inst->setAccess(PrevClassTemplate->getAccess());
813 else
814 Inst->setAccess(D->getAccess());
815
John McCall93ba8572010-03-25 06:39:04 +0000816 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
817 // TODO: do we want to track the instantiation progeny of this
818 // friend target decl?
819 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000820 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000821 Inst->setInstantiatedFromMemberTemplate(D);
822 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000823
824 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000825 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000826 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000827
Douglas Gregor259571e2009-10-30 22:42:42 +0000828 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000829 if (isFriend) {
830 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000831 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000832 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000833
John McCalle29ba202009-08-20 01:44:21 +0000834 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000835
Douglas Gregored9c0f92009-10-29 00:04:11 +0000836 // Instantiate all of the partial specializations of this member class
837 // template.
Douglas Gregordc60c1e2010-04-30 05:56:50 +0000838 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
839 D->getPartialSpecializations(PartialSpecs);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000840 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
841 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
842
John McCalle29ba202009-08-20 01:44:21 +0000843 return Inst;
844}
845
Douglas Gregord60e1052009-08-27 16:57:43 +0000846Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000847TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
848 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000849 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
850
851 // Lookup the already-instantiated declaration in the instantiation
852 // of the class template and return that.
853 DeclContext::lookup_result Found
854 = Owner->lookup(ClassTemplate->getDeclName());
855 if (Found.first == Found.second)
856 return 0;
857
858 ClassTemplateDecl *InstClassTemplate
859 = dyn_cast<ClassTemplateDecl>(*Found.first);
860 if (!InstClassTemplate)
861 return 0;
862
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +0000863 return InstClassTemplate->findPartialSpecInstantiatedFromMember(D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000864}
865
866Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000867TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000868 // Create a local instantiation scope for this function template, which
869 // will contain the instantiations of the template parameters and then get
870 // merged with the local instantiation scope for the function template
871 // itself.
872 Sema::LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000873
Douglas Gregord60e1052009-08-27 16:57:43 +0000874 TemplateParameterList *TempParams = D->getTemplateParameters();
875 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000876 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000877 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000878
Douglas Gregora735b202009-10-13 14:39:41 +0000879 FunctionDecl *Instantiated = 0;
880 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
881 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
882 InstParams));
883 else
884 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
885 D->getTemplatedDecl(),
886 InstParams));
887
888 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000889 return 0;
890
John McCall46460a62010-01-20 21:53:11 +0000891 Instantiated->setAccess(D->getAccess());
892
Mike Stump1eb44332009-09-09 15:08:12 +0000893 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000894 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000895 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000896 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000897 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000898 assert(InstTemplate &&
899 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000900
John McCallb1a56e72010-03-26 23:10:15 +0000901 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
902
John McCalle976ffe2009-12-14 23:19:40 +0000903 // Link the instantiation back to the pattern *unless* this is a
904 // non-definition friend declaration.
905 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000906 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000907 InstTemplate->setInstantiatedFromMemberTemplate(D);
908
John McCallb1a56e72010-03-26 23:10:15 +0000909 // Make declarations visible in the appropriate context.
910 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000911 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000912
Douglas Gregord60e1052009-08-27 16:57:43 +0000913 return InstTemplate;
914}
915
Douglas Gregord475b8d2009-03-25 21:17:03 +0000916Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
917 CXXRecordDecl *PrevDecl = 0;
918 if (D->isInjectedClassName())
919 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000920 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000921 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
922 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000923 TemplateArgs);
924 if (!Prev) return 0;
925 PrevDecl = cast<CXXRecordDecl>(Prev);
926 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000927
928 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000929 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000930 D->getLocation(), D->getIdentifier(),
931 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000932
933 // Substitute the nested name specifier, if any.
934 if (SubstQualifier(D, Record))
935 return 0;
936
Douglas Gregord475b8d2009-03-25 21:17:03 +0000937 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000938 // FIXME: Check against AS_none is an ugly hack to work around the issue that
939 // the tag decls introduced by friend class declarations don't have an access
940 // specifier. Remove once this area of the code gets sorted out.
941 if (D->getAccess() != AS_none)
942 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000943 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000944 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000945
John McCall02cace72009-08-28 07:59:38 +0000946 // If the original function was part of a friend declaration,
947 // inherit its namespace state.
948 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
949 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
950
Douglas Gregor9901c572010-05-21 00:31:19 +0000951 // Make sure that anonymous structs and unions are recorded.
952 if (D->isAnonymousStructOrUnion()) {
953 Record->setAnonymousStructOrUnion(true);
954 if (Record->getDeclContext()->getLookupContext()->isFunctionOrMethod())
955 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
956 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000957
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000958 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000959 return Record;
960}
961
John McCall02cace72009-08-28 07:59:38 +0000962/// Normal class members are of more specific types and therefore
963/// don't make it here. This function serves two purposes:
964/// 1) instantiating function templates
965/// 2) substituting friend declarations
966/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000967Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000968 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000969 // Check whether there is already a function template specialization for
970 // this declaration.
971 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
972 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000973 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000974 std::pair<const TemplateArgument *, unsigned> Innermost
975 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000977 FunctionDecl *SpecFunc
978 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
979 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Douglas Gregor127102b2009-06-29 20:59:39 +0000981 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000982 if (SpecFunc)
983 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000984 }
Mike Stump1eb44332009-09-09 15:08:12 +0000985
John McCallb0cb0222010-03-27 05:57:59 +0000986 bool isFriend;
987 if (FunctionTemplate)
988 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
989 else
990 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
991
Douglas Gregor79c22782010-01-16 20:21:20 +0000992 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000993 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000994 !(isa<Decl>(Owner) &&
995 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
996 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Douglas Gregore53060f2009-06-25 22:08:12 +0000998 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000999 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1000 TInfo = SubstFunctionType(D, Params);
1001 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001002 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001003 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001004
John McCalld325daa2010-03-26 04:53:08 +00001005 NestedNameSpecifier *Qualifier = D->getQualifier();
1006 if (Qualifier) {
1007 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1008 D->getQualifierRange(),
1009 TemplateArgs);
1010 if (!Qualifier) return 0;
1011 }
1012
John McCall68b6b872010-02-06 01:50:47 +00001013 // If we're instantiating a local function declaration, put the result
1014 // in the owner; otherwise we need to find the instantiated context.
1015 DeclContext *DC;
1016 if (D->getDeclContext()->isFunctionOrMethod())
1017 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001018 else if (isFriend && Qualifier) {
1019 CXXScopeSpec SS;
1020 SS.setScopeRep(Qualifier);
1021 SS.setRange(D->getQualifierRange());
1022 DC = SemaRef.computeDeclContext(SS);
1023 if (!DC) return 0;
1024 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001025 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1026 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001027 }
John McCall68b6b872010-02-06 01:50:47 +00001028
John McCall02cace72009-08-28 07:59:38 +00001029 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001030 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001031 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001032 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001033 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001034
John McCalld325daa2010-03-26 04:53:08 +00001035 if (Qualifier)
1036 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001037
John McCallb1a56e72010-03-26 23:10:15 +00001038 DeclContext *LexicalDC = Owner;
1039 if (!isFriend && D->isOutOfLine()) {
1040 assert(D->getDeclContext()->isFileContext());
1041 LexicalDC = D->getDeclContext();
1042 }
1043
1044 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregore53060f2009-06-25 22:08:12 +00001046 // Attach the parameters
1047 for (unsigned P = 0; P < Params.size(); ++P)
1048 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001049 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001050
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001051 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001052 if (TemplateParams) {
1053 // Our resulting instantiation is actually a function template, since we
1054 // are substituting only the outer template parameters. For example, given
1055 //
1056 // template<typename T>
1057 // struct X {
1058 // template<typename U> friend void f(T, U);
1059 // };
1060 //
1061 // X<int> x;
1062 //
1063 // We are instantiating the friend function template "f" within X<int>,
1064 // which means substituting int for T, but leaving "f" as a friend function
1065 // template.
1066 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001067 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001068 Function->getLocation(),
1069 Function->getDeclName(),
1070 TemplateParams, Function);
1071 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001072
1073 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001074
1075 if (isFriend && D->isThisDeclarationADefinition()) {
1076 // TODO: should we remember this connection regardless of whether
1077 // the friend declaration provided a body?
1078 FunctionTemplate->setInstantiatedFromMemberTemplate(
1079 D->getDescribedFunctionTemplate());
1080 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001081 } else if (FunctionTemplate) {
1082 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001083 std::pair<const TemplateArgument *, unsigned> Innermost
1084 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001085 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001086 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1087 Innermost.first,
1088 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001089 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001090 } else if (isFriend && D->isThisDeclarationADefinition()) {
1091 // TODO: should we remember this connection regardless of whether
1092 // the friend declaration provided a body?
1093 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001094 }
Douglas Gregora735b202009-10-13 14:39:41 +00001095
Douglas Gregore53060f2009-06-25 22:08:12 +00001096 if (InitFunctionInstantiation(Function, D))
1097 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregore53060f2009-06-25 22:08:12 +00001099 bool Redeclaration = false;
1100 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001101 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001102
John McCall68263142009-11-18 22:49:29 +00001103 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1104 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1105
John McCallaf2094e2010-04-08 09:05:18 +00001106 if (DependentFunctionTemplateSpecializationInfo *Info
1107 = D->getDependentSpecializationInfo()) {
1108 assert(isFriend && "non-friend has dependent specialization info?");
1109
1110 // This needs to be set now for future sanity.
1111 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1112
1113 // Instantiate the explicit template arguments.
1114 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1115 Info->getRAngleLoc());
1116 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1117 TemplateArgumentLoc Loc;
1118 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1119 return 0;
1120
1121 ExplicitArgs.addArgument(Loc);
1122 }
1123
1124 // Map the candidate templates to their instantiations.
1125 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1126 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1127 Info->getTemplate(I),
1128 TemplateArgs);
1129 if (!Temp) return 0;
1130
1131 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1132 }
1133
1134 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1135 &ExplicitArgs,
1136 Previous))
1137 Function->setInvalidDecl();
1138
1139 isExplicitSpecialization = true;
1140
1141 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001142 // Look only into the namespace where the friend would be declared to
1143 // find a previous declaration. This is the innermost enclosing namespace,
1144 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001145 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001146
Douglas Gregora735b202009-10-13 14:39:41 +00001147 // In C++, the previous declaration we find might be a tag type
1148 // (class or enum). In this case, the new declaration will hide the
1149 // tag type. Note that this does does not apply if we're declaring a
1150 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001151 if (Previous.isSingleTagDecl())
1152 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001153 }
1154
John McCall9f54ad42009-12-10 09:41:52 +00001155 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001156 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001157 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001158
John McCall76d32642010-04-24 01:30:58 +00001159 NamedDecl *PrincipalDecl = (TemplateParams
1160 ? cast<NamedDecl>(FunctionTemplate)
1161 : Function);
1162
Douglas Gregora735b202009-10-13 14:39:41 +00001163 // If the original function was part of a friend declaration,
1164 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001165 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001166 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001167 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001168 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001169 else
Douglas Gregora735b202009-10-13 14:39:41 +00001170 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001171
1172 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1173 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregor238058c2010-05-18 05:45:02 +00001174
1175 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1176 D->isThisDeclarationADefinition()) {
1177 // Check for a function body.
1178 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001179 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001180 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1181 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1182 << Function->getDeclName();
1183 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1184 Function->setInvalidDecl();
1185 }
1186 // Check for redefinitions due to other instantiations of this or
1187 // a similar friend function.
1188 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1189 REnd = Function->redecls_end();
1190 R != REnd; ++R) {
1191 if (*R != Function &&
1192 ((*R)->getFriendObjectKind() != Decl::FOK_None)) {
1193 if (const FunctionDecl *RPattern
1194 = (*R)->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001195 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001196 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1197 << Function->getDeclName();
1198 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition);
1199 Function->setInvalidDecl();
1200 break;
1201 }
1202 }
1203 }
1204 }
1205
Douglas Gregora735b202009-10-13 14:39:41 +00001206 }
1207
John McCall76d32642010-04-24 01:30:58 +00001208 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1209 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1210 PrincipalDecl->setNonMemberOperator();
1211
Douglas Gregore53060f2009-06-25 22:08:12 +00001212 return Function;
1213}
1214
Douglas Gregord60e1052009-08-27 16:57:43 +00001215Decl *
1216TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1217 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001218 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1219 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001220 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 // We are creating a function template specialization from a function
1222 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001223 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001224 std::pair<const TemplateArgument *, unsigned> Innermost
1225 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001227 FunctionDecl *SpecFunc
1228 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1229 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Douglas Gregor6b906862009-08-21 00:16:32 +00001231 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001232 if (SpecFunc)
1233 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001234 }
1235
John McCallb0cb0222010-03-27 05:57:59 +00001236 bool isFriend;
1237 if (FunctionTemplate)
1238 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1239 else
1240 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1241
Douglas Gregor79c22782010-01-16 20:21:20 +00001242 bool MergeWithParentScope = (TemplateParams != 0) ||
1243 !(isa<Decl>(Owner) &&
1244 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1245 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001246
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001247 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001248 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1249 TInfo = SubstFunctionType(D, Params);
1250 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001251 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001252 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001253
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001254 // \brief If the type of this function is not *directly* a function
1255 // type, then we're instantiating the a function that was declared
1256 // via a typedef, e.g.,
1257 //
1258 // typedef int functype(int, int);
1259 // functype func;
1260 //
1261 // In this case, we'll just go instantiate the ParmVarDecls that we
1262 // synthesized in the method declaration.
1263 if (!isa<FunctionProtoType>(T)) {
1264 assert(!Params.size() && "Instantiating type could not yield parameters");
1265 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1266 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1267 TemplateArgs);
1268 if (!P)
1269 return 0;
1270
1271 Params.push_back(P);
1272 }
1273 }
1274
John McCallb0cb0222010-03-27 05:57:59 +00001275 NestedNameSpecifier *Qualifier = D->getQualifier();
1276 if (Qualifier) {
1277 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1278 D->getQualifierRange(),
1279 TemplateArgs);
1280 if (!Qualifier) return 0;
1281 }
1282
1283 DeclContext *DC = Owner;
1284 if (isFriend) {
1285 if (Qualifier) {
1286 CXXScopeSpec SS;
1287 SS.setScopeRep(Qualifier);
1288 SS.setRange(D->getQualifierRange());
1289 DC = SemaRef.computeDeclContext(SS);
1290 } else {
1291 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1292 D->getDeclContext(),
1293 TemplateArgs);
1294 }
1295 if (!DC) return 0;
1296 }
1297
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001298 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001299 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001300 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Abramo Bagnara25777432010-08-11 22:01:17 +00001302 DeclarationNameInfo NameInfo
1303 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001304 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001305 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001306 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001307 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001308 Constructor->isInlineSpecified(),
1309 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001310 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001311 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001312 NameInfo, T,
1313 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001314 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001315 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001316 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001317 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001318 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001319 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001320 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001321 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1322 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001323 D->isStatic(),
1324 D->getStorageClassAsWritten(),
1325 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001326 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001327
John McCallb0cb0222010-03-27 05:57:59 +00001328 if (Qualifier)
1329 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001330
Douglas Gregord60e1052009-08-27 16:57:43 +00001331 if (TemplateParams) {
1332 // Our resulting instantiation is actually a function template, since we
1333 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001334 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001335 // template<typename T>
1336 // struct X {
1337 // template<typename U> void f(T, U);
1338 // };
1339 //
1340 // X<int> x;
1341 //
1342 // We are instantiating the member template "f" within X<int>, which means
1343 // substituting int for T, but leaving "f" as a member function template.
1344 // Build the function template itself.
1345 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1346 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001347 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001348 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001349 if (isFriend) {
1350 FunctionTemplate->setLexicalDeclContext(Owner);
1351 FunctionTemplate->setObjectOfFriendDecl(true);
1352 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001353 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001354 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001355 } else if (FunctionTemplate) {
1356 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001357 std::pair<const TemplateArgument *, unsigned> Innermost
1358 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001359 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001360 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1361 Innermost.first,
1362 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001363 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001364 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001365 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001366 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001367 }
1368
Mike Stump1eb44332009-09-09 15:08:12 +00001369 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001370 // out-of-line, the instantiation will have the same lexical
1371 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001372 if (isFriend) {
1373 Method->setLexicalDeclContext(Owner);
1374 Method->setObjectOfFriendDecl(true);
1375 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001376 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Douglas Gregor5545e162009-03-24 00:38:23 +00001378 // Attach the parameters
1379 for (unsigned P = 0; P < Params.size(); ++P)
1380 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001381 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001382
1383 if (InitMethodInstantiation(Method, D))
1384 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001385
Abramo Bagnara25777432010-08-11 22:01:17 +00001386 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1387 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001388
John McCallb0cb0222010-03-27 05:57:59 +00001389 if (!FunctionTemplate || TemplateParams || isFriend) {
1390 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Douglas Gregordec06662009-08-21 18:42:58 +00001392 // In C++, the previous declaration we find might be a tag type
1393 // (class or enum). In this case, the new declaration will hide the
1394 // tag type. Note that this does does not apply if we're declaring a
1395 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001396 if (Previous.isSingleTagDecl())
1397 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001398 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001399
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001400 bool Redeclaration = false;
1401 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001402 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001403 /*FIXME:*/OverloadableAttrRequired);
1404
Douglas Gregor4ba31362009-12-01 17:24:26 +00001405 if (D->isPure())
1406 SemaRef.CheckPureMethod(Method, SourceRange());
1407
John McCall46460a62010-01-20 21:53:11 +00001408 Method->setAccess(D->getAccess());
1409
John McCallb0cb0222010-03-27 05:57:59 +00001410 if (FunctionTemplate) {
1411 // If there's a function template, let our caller handle it.
1412 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1413 // Don't hide a (potentially) valid declaration with an invalid one.
1414 } else {
1415 NamedDecl *DeclToAdd = (TemplateParams
1416 ? cast<NamedDecl>(FunctionTemplate)
1417 : Method);
1418 if (isFriend)
1419 Record->makeDeclVisibleInContext(DeclToAdd);
1420 else
1421 Owner->addDecl(DeclToAdd);
1422 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001423
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001424 return Method;
1425}
1426
Douglas Gregor615c5d42009-03-24 16:43:20 +00001427Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001428 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001429}
1430
Douglas Gregor03b2b072009-03-24 00:15:49 +00001431Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001432 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001433}
1434
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001435Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001436 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001437}
1438
Douglas Gregor6477b692009-03-25 15:04:13 +00001439ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001440 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001441}
1442
John McCalle29ba202009-08-20 01:44:21 +00001443Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1444 TemplateTypeParmDecl *D) {
1445 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001446 const Type* T = D->getTypeForDecl();
1447 assert(T->isTemplateTypeParmType());
1448 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001449
John McCalle29ba202009-08-20 01:44:21 +00001450 TemplateTypeParmDecl *Inst =
1451 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregorefed5c82010-06-16 15:23:05 +00001452 TTPT->getDepth() - 1, TTPT->getIndex(),
1453 TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001454 D->wasDeclaredWithTypename(),
1455 D->isParameterPack());
1456
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001457 if (D->hasDefaultArgument())
1458 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001459
Douglas Gregor550d9b22009-10-31 17:21:17 +00001460 // Introduce this template parameter's instantiation into the instantiation
1461 // scope.
1462 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1463
John McCalle29ba202009-08-20 01:44:21 +00001464 return Inst;
1465}
1466
Douglas Gregor33642df2009-10-23 23:25:44 +00001467Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1468 NonTypeTemplateParmDecl *D) {
1469 // Substitute into the type of the non-type template parameter.
1470 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001471 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001472 if (DI) {
1473 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1474 D->getDeclName());
1475 if (DI) T = DI->getType();
1476 } else {
1477 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1478 D->getDeclName());
1479 DI = 0;
1480 }
1481 if (T.isNull())
1482 return 0;
1483
1484 // Check that this type is acceptable for a non-type template parameter.
1485 bool Invalid = false;
1486 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1487 if (T.isNull()) {
1488 T = SemaRef.Context.IntTy;
1489 Invalid = true;
1490 }
1491
1492 NonTypeTemplateParmDecl *Param
1493 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1494 D->getDepth() - 1, D->getPosition(),
1495 D->getIdentifier(), T, DI);
1496 if (Invalid)
1497 Param->setInvalidDecl();
1498
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001499 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001500
1501 // Introduce this template parameter's instantiation into the instantiation
1502 // scope.
1503 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001504 return Param;
1505}
1506
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001507Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001508TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1509 TemplateTemplateParmDecl *D) {
1510 // Instantiate the template parameter list of the template template parameter.
1511 TemplateParameterList *TempParams = D->getTemplateParameters();
1512 TemplateParameterList *InstParams;
1513 {
1514 // Perform the actual substitution of template parameters within a new,
1515 // local instantiation scope.
1516 Sema::LocalInstantiationScope Scope(SemaRef);
1517 InstParams = SubstTemplateParams(TempParams);
1518 if (!InstParams)
1519 return NULL;
1520 }
1521
1522 // Build the template template parameter.
1523 TemplateTemplateParmDecl *Param
1524 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1525 D->getDepth() - 1, D->getPosition(),
1526 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001527 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001528
Douglas Gregor9106ef72009-11-11 16:58:32 +00001529 // Introduce this template parameter's instantiation into the instantiation
1530 // scope.
1531 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1532
1533 return Param;
1534}
1535
Douglas Gregor48c32a72009-11-17 06:07:40 +00001536Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1537 // Using directives are never dependent, so they require no explicit
1538
1539 UsingDirectiveDecl *Inst
1540 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1541 D->getNamespaceKeyLocation(),
1542 D->getQualifierRange(), D->getQualifier(),
1543 D->getIdentLocation(),
1544 D->getNominatedNamespace(),
1545 D->getCommonAncestor());
1546 Owner->addDecl(Inst);
1547 return Inst;
1548}
1549
John McCalled976492009-12-04 22:46:56 +00001550Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1551 // The nested name specifier is non-dependent, so no transformation
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001552 // is required. The same holds for the name info.
1553 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001554
John McCall9f54ad42009-12-10 09:41:52 +00001555 // We only need to do redeclaration lookups if we're in a class
1556 // scope (in fact, it's not really even possible in non-class
1557 // scopes).
1558 bool CheckRedeclaration = Owner->isRecord();
1559
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001560 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1561 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001562
John McCalled976492009-12-04 22:46:56 +00001563 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001564 D->getNestedNameRange(),
1565 D->getUsingLocation(),
1566 D->getTargetNestedNameDecl(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001567 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001568 D->isTypeName());
1569
1570 CXXScopeSpec SS;
1571 SS.setScopeRep(D->getTargetNestedNameDecl());
1572 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001573
1574 if (CheckRedeclaration) {
1575 Prev.setHideTags(false);
1576 SemaRef.LookupQualifiedName(Prev, Owner);
1577
1578 // Check for invalid redeclarations.
1579 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1580 D->isTypeName(), SS,
1581 D->getLocation(), Prev))
1582 NewUD->setInvalidDecl();
1583
1584 }
1585
1586 if (!NewUD->isInvalidDecl() &&
1587 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001588 D->getLocation()))
1589 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001590
John McCalled976492009-12-04 22:46:56 +00001591 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1592 NewUD->setAccess(D->getAccess());
1593 Owner->addDecl(NewUD);
1594
John McCall9f54ad42009-12-10 09:41:52 +00001595 // Don't process the shadow decls for an invalid decl.
1596 if (NewUD->isInvalidDecl())
1597 return NewUD;
1598
John McCall323c3102009-12-22 22:26:37 +00001599 bool isFunctionScope = Owner->isFunctionOrMethod();
1600
John McCall9f54ad42009-12-10 09:41:52 +00001601 // Process the shadow decls.
1602 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1603 I != E; ++I) {
1604 UsingShadowDecl *Shadow = *I;
1605 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001606 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1607 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001608 TemplateArgs));
1609
1610 if (CheckRedeclaration &&
1611 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1612 continue;
1613
1614 UsingShadowDecl *InstShadow
1615 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1616 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001617
1618 if (isFunctionScope)
1619 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001620 }
John McCalled976492009-12-04 22:46:56 +00001621
1622 return NewUD;
1623}
1624
1625Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001626 // Ignore these; we handle them in bulk when processing the UsingDecl.
1627 return 0;
John McCalled976492009-12-04 22:46:56 +00001628}
1629
John McCall7ba107a2009-11-18 02:36:19 +00001630Decl * TemplateDeclInstantiator
1631 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001632 NestedNameSpecifier *NNS =
1633 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1634 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001635 TemplateArgs);
1636 if (!NNS)
1637 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001639 CXXScopeSpec SS;
1640 SS.setRange(D->getTargetNestedNameRange());
1641 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001643 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1644 // Hence, no tranformation is required for it.
1645 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001646 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001647 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001648 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001649 /*instantiation*/ true,
1650 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001651 if (UD)
John McCalled976492009-12-04 22:46:56 +00001652 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1653
John McCall7ba107a2009-11-18 02:36:19 +00001654 return UD;
1655}
1656
1657Decl * TemplateDeclInstantiator
1658 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1659 NestedNameSpecifier *NNS =
1660 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1661 D->getTargetNestedNameRange(),
1662 TemplateArgs);
1663 if (!NNS)
1664 return 0;
1665
1666 CXXScopeSpec SS;
1667 SS.setRange(D->getTargetNestedNameRange());
1668 SS.setScopeRep(NNS);
1669
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001670 DeclarationNameInfo NameInfo
1671 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1672
John McCall7ba107a2009-11-18 02:36:19 +00001673 NamedDecl *UD =
1674 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001675 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001676 /*instantiation*/ true,
1677 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001678 if (UD)
John McCalled976492009-12-04 22:46:56 +00001679 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1680
Anders Carlsson0d8df782009-08-29 19:37:28 +00001681 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001682}
1683
John McCallce3ff2b2009-08-25 22:02:44 +00001684Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001685 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001686 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001687 if (D->isInvalidDecl())
1688 return 0;
1689
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001690 return Instantiator.Visit(D);
1691}
1692
John McCalle29ba202009-08-20 01:44:21 +00001693/// \brief Instantiates a nested template parameter list in the current
1694/// instantiation context.
1695///
1696/// \param L The parameter list to instantiate
1697///
1698/// \returns NULL if there was an error
1699TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001700TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001701 // Get errors for all the parameters before bailing out.
1702 bool Invalid = false;
1703
1704 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001705 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001706 ParamVector Params;
1707 Params.reserve(N);
1708 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1709 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001710 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001711 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001712 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001713 }
1714
1715 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001716 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001717 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001718
1719 TemplateParameterList *InstL
1720 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1721 L->getLAngleLoc(), &Params.front(), N,
1722 L->getRAngleLoc());
1723 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001724}
John McCalle29ba202009-08-20 01:44:21 +00001725
Douglas Gregored9c0f92009-10-29 00:04:11 +00001726/// \brief Instantiate the declaration of a class template partial
1727/// specialization.
1728///
1729/// \param ClassTemplate the (instantiated) class template that is partially
1730// specialized by the instantiation of \p PartialSpec.
1731///
1732/// \param PartialSpec the (uninstantiated) class template partial
1733/// specialization that we are instantiating.
1734///
1735/// \returns true if there was an error, false otherwise.
1736bool
1737TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1738 ClassTemplateDecl *ClassTemplate,
1739 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001740 // Create a local instantiation scope for this class template partial
1741 // specialization, which will contain the instantiations of the template
1742 // parameters.
1743 Sema::LocalInstantiationScope Scope(SemaRef);
1744
Douglas Gregored9c0f92009-10-29 00:04:11 +00001745 // Substitute into the template parameters of the class template partial
1746 // specialization.
1747 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1748 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1749 if (!InstParams)
1750 return true;
1751
1752 // Substitute into the template arguments of the class template partial
1753 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001754 const TemplateArgumentLoc *PartialSpecTemplateArgs
1755 = PartialSpec->getTemplateArgsAsWritten();
1756 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1757
John McCalld5532b62009-11-23 01:53:49 +00001758 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001759 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001760 TemplateArgumentLoc Loc;
1761 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001762 return true;
John McCalld5532b62009-11-23 01:53:49 +00001763 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001764 }
1765
1766
1767 // Check that the template argument list is well-formed for this
1768 // class template.
1769 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1770 InstTemplateArgs.size());
1771 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1772 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001773 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001774 false,
1775 Converted))
1776 return true;
1777
1778 // Figure out where to insert this class template partial specialization
1779 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001780 void *InsertPos = 0;
1781 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001782 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
1783 Converted.flatSize(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001784
1785 // Build the canonical type that describes the converted template
1786 // arguments of the class template partial specialization.
1787 QualType CanonType
1788 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1789 Converted.getFlatArguments(),
1790 Converted.flatSize());
1791
1792 // Build the fully-sugared type for this class template
1793 // specialization as the user wrote in the specialization
1794 // itself. This means that we'll pretty-print the type retrieved
1795 // from the specialization's declaration the way that the user
1796 // actually wrote the specialization, rather than formatting the
1797 // name based on the "canonical" representation used to store the
1798 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001799 TypeSourceInfo *WrittenTy
1800 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1801 TemplateName(ClassTemplate),
1802 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001803 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001804 CanonType);
1805
1806 if (PrevDecl) {
1807 // We've already seen a partial specialization with the same template
1808 // parameters and template arguments. This can happen, for example, when
1809 // substituting the outer template arguments ends up causing two
1810 // class template partial specializations of a member class template
1811 // to have identical forms, e.g.,
1812 //
1813 // template<typename T, typename U>
1814 // struct Outer {
1815 // template<typename X, typename Y> struct Inner;
1816 // template<typename Y> struct Inner<T, Y>;
1817 // template<typename Y> struct Inner<U, Y>;
1818 // };
1819 //
1820 // Outer<int, int> outer; // error: the partial specializations of Inner
1821 // // have the same signature.
1822 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1823 << WrittenTy;
1824 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1825 << SemaRef.Context.getTypeDeclType(PrevDecl);
1826 return true;
1827 }
1828
1829
1830 // Create the class template partial specialization declaration.
1831 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001832 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1833 PartialSpec->getTagKind(),
1834 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001835 PartialSpec->getLocation(),
1836 InstParams,
1837 ClassTemplate,
1838 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001839 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001840 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001841 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001842 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001843 // Substitute the nested name specifier, if any.
1844 if (SubstQualifier(PartialSpec, InstPartialSpec))
1845 return 0;
1846
Douglas Gregored9c0f92009-10-29 00:04:11 +00001847 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001848 InstPartialSpec->setTypeAsWritten(WrittenTy);
1849
Douglas Gregored9c0f92009-10-29 00:04:11 +00001850 // Add this partial specialization to the set of class template partial
1851 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001852 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001853 return false;
1854}
1855
John McCall21ef0fa2010-03-11 09:03:00 +00001856TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001857TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001858 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001859 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1860 assert(OldTInfo && "substituting function without type source info");
1861 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001862 TypeSourceInfo *NewTInfo
1863 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1864 D->getTypeSpecStartLoc(),
1865 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001866 if (!NewTInfo)
1867 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001868
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001869 if (NewTInfo != OldTInfo) {
1870 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001871 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001872 if (FunctionProtoTypeLoc *OldProtoLoc
1873 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1874 TypeLoc NewTL = NewTInfo->getTypeLoc();
1875 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1876 assert(NewProtoLoc && "Missing prototype?");
1877 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1878 // FIXME: Variadic templates will break this.
1879 Params.push_back(NewProtoLoc->getArg(i));
1880 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001881 OldProtoLoc->getArg(i),
1882 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001883 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001884 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001885 } else {
1886 // The function type itself was not dependent and therefore no
1887 // substitution occurred. However, we still need to instantiate
1888 // the function parameters themselves.
1889 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001890 if (FunctionProtoTypeLoc *OldProtoLoc
1891 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1892 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1893 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1894 if (!Parm)
1895 return 0;
1896 Params.push_back(Parm);
1897 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001898 }
1899 }
John McCall21ef0fa2010-03-11 09:03:00 +00001900 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001901}
1902
Mike Stump1eb44332009-09-09 15:08:12 +00001903/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001904/// declaration (New) from the corresponding fields of its template (Tmpl).
1905///
1906/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001907bool
1908TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001909 FunctionDecl *Tmpl) {
1910 if (Tmpl->isDeleted())
1911 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Douglas Gregorcca9e962009-07-01 22:01:06 +00001913 // If we are performing substituting explicitly-specified template arguments
1914 // or deduced template arguments into a function template and we reach this
1915 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001916 // to keeping the new function template specialization. We therefore
1917 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001918 // into a template instantiation for this specific function template
1919 // specialization, which is not a SFINAE context, so that we diagnose any
1920 // further errors in the declaration itself.
1921 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1922 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1923 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1924 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001925 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001926 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001927 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001928 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001929 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001930 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1931 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001932 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001933 }
1934 }
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001936 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1937 assert(Proto && "Function template without prototype?");
1938
1939 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1940 Proto->getNoReturnAttr()) {
1941 // The function has an exception specification or a "noreturn"
1942 // attribute. Substitute into each of the exception types.
1943 llvm::SmallVector<QualType, 4> Exceptions;
1944 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1945 // FIXME: Poor location information!
1946 QualType T
1947 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1948 New->getLocation(), New->getDeclName());
1949 if (T.isNull() ||
1950 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1951 continue;
1952
1953 Exceptions.push_back(T);
1954 }
1955
1956 // Rebuild the function type
1957
1958 const FunctionProtoType *NewProto
1959 = New->getType()->getAs<FunctionProtoType>();
1960 assert(NewProto && "Template instantiation without function prototype?");
1961 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1962 NewProto->arg_type_begin(),
1963 NewProto->getNumArgs(),
1964 NewProto->isVariadic(),
1965 NewProto->getTypeQuals(),
1966 Proto->hasExceptionSpec(),
1967 Proto->hasAnyExceptionSpec(),
1968 Exceptions.size(),
1969 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001970 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001971 }
1972
John McCall1d8d1cc2010-08-01 02:01:53 +00001973 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00001974
Douglas Gregore53060f2009-06-25 22:08:12 +00001975 return false;
1976}
1977
Douglas Gregor5545e162009-03-24 00:38:23 +00001978/// \brief Initializes common fields of an instantiated method
1979/// declaration (New) from the corresponding fields of its template
1980/// (Tmpl).
1981///
1982/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001983bool
1984TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001985 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001986 if (InitFunctionInstantiation(New, Tmpl))
1987 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Douglas Gregor5545e162009-03-24 00:38:23 +00001989 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1990 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001991 if (Tmpl->isVirtualAsWritten())
1992 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001993
1994 // FIXME: attributes
1995 // FIXME: New needs a pointer to Tmpl
1996 return false;
1997}
Douglas Gregora58861f2009-05-13 20:28:22 +00001998
1999/// \brief Instantiate the definition of the given function from its
2000/// template.
2001///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002002/// \param PointOfInstantiation the point at which the instantiation was
2003/// required. Note that this is not precisely a "point of instantiation"
2004/// for the function, but it's close.
2005///
Douglas Gregora58861f2009-05-13 20:28:22 +00002006/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002007/// function template specialization or member function of a class template
2008/// specialization.
2009///
2010/// \param Recursive if true, recursively instantiates any functions that
2011/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002012///
2013/// \param DefinitionRequired if true, then we are performing an explicit
2014/// instantiation where the body of the function is required. Complain if
2015/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002016void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002017 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002018 bool Recursive,
2019 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002020 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002021 return;
2022
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002023 // Never instantiate an explicit specialization.
2024 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2025 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002026
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002027 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002028 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002029 Stmt *Pattern = 0;
2030 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002031 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002032
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002033 if (!Pattern) {
2034 if (DefinitionRequired) {
2035 if (Function->getPrimaryTemplate())
2036 Diag(PointOfInstantiation,
2037 diag::err_explicit_instantiation_undefined_func_template)
2038 << Function->getPrimaryTemplate();
2039 else
2040 Diag(PointOfInstantiation,
2041 diag::err_explicit_instantiation_undefined_member)
2042 << 1 << Function->getDeclName() << Function->getDeclContext();
2043
2044 if (PatternDecl)
2045 Diag(PatternDecl->getLocation(),
2046 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002047 Function->setInvalidDecl();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002048 }
2049
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002050 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002051 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002052
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002053 // C++0x [temp.explicit]p9:
2054 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002055 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002056 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002057 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002058 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002059 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002060 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002062 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2063 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002064 return;
2065
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002066 // If we're performing recursive template instantiation, create our own
2067 // queue of pending implicit instantiations that we will instantiate later,
2068 // while we're still within our own instantiation context.
2069 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2070 if (Recursive)
2071 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Douglas Gregor9679caf2010-05-12 17:27:19 +00002073 EnterExpressionEvaluationContext EvalContext(*this,
2074 Action::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002075 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2076
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002077 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002078 // recorded, unless we're actually a member function within a local
2079 // class, in which case we need to merge our results with the parent
2080 // scope (of the enclosing function).
2081 bool MergeWithParentScope = false;
2082 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2083 MergeWithParentScope = Rec->isLocalClass();
2084
2085 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002087 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002088 // instantiation scope, and set the parameter names to those used
2089 // in the template.
2090 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2091 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2092 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2093 FunctionParam->setDeclName(PatternParam->getDeclName());
2094 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2095 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002096
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002097 // Enter the scope of this instantiation. We don't use
2098 // PushDeclContext because we don't have a scope.
2099 DeclContext *PreviousContext = CurContext;
2100 CurContext = Function;
2101
Mike Stump1eb44332009-09-09 15:08:12 +00002102 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002103 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002104
2105 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002106 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002107 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2108 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2109 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002110 }
2111
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002112 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002113 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002114
Douglas Gregor52604ab2009-09-11 21:19:12 +00002115 if (Body.isInvalid())
2116 Function->setInvalidDecl();
2117
Mike Stump1eb44332009-09-09 15:08:12 +00002118 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002119 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002120
John McCall0c01d182010-03-24 05:22:00 +00002121 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2122
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002123 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002124
2125 DeclGroupRef DG(Function);
2126 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Douglas Gregor60406be2010-01-16 22:29:39 +00002128 // This class may have local implicit instantiations that need to be
2129 // instantiation within this scope.
2130 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2131 Scope.Exit();
2132
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002133 if (Recursive) {
2134 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002135 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002136 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002138 // Restore the set of pending implicit instantiations.
2139 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2140 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002141}
2142
2143/// \brief Instantiate the definition of the given variable from its
2144/// template.
2145///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002146/// \param PointOfInstantiation the point at which the instantiation was
2147/// required. Note that this is not precisely a "point of instantiation"
2148/// for the function, but it's close.
2149///
2150/// \param Var the already-instantiated declaration of a static member
2151/// variable of a class template specialization.
2152///
2153/// \param Recursive if true, recursively instantiates any functions that
2154/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002155///
2156/// \param DefinitionRequired if true, then we are performing an explicit
2157/// instantiation where an out-of-line definition of the member variable
2158/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002159void Sema::InstantiateStaticDataMemberDefinition(
2160 SourceLocation PointOfInstantiation,
2161 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002162 bool Recursive,
2163 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002164 if (Var->isInvalidDecl())
2165 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregor7caa6822009-07-24 20:34:43 +00002167 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002168 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002169 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002170 assert(Def->isStaticDataMember() && "Not a static data member?");
2171 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Douglas Gregor0d035142009-10-27 18:42:08 +00002173 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002174 // We did not find an out-of-line definition of this static data member,
2175 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002176 // instantiate this definition (or provide a specialization for it) in
2177 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002178 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002179 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002180 Diag(PointOfInstantiation,
2181 diag::err_explicit_instantiation_undefined_member)
2182 << 2 << Var->getDeclName() << Var->getDeclContext();
2183 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2184 }
2185
Douglas Gregor7caa6822009-07-24 20:34:43 +00002186 return;
2187 }
2188
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002189 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002190 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002191 return;
2192
2193 // C++0x [temp.explicit]p9:
2194 // Except for inline functions, other explicit instantiation declarations
2195 // have the effect of suppressing the implicit instantiation of the entity
2196 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002197 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002198 == TSK_ExplicitInstantiationDeclaration)
2199 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Douglas Gregor7caa6822009-07-24 20:34:43 +00002201 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2202 if (Inst)
2203 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Douglas Gregor7caa6822009-07-24 20:34:43 +00002205 // If we're performing recursive template instantiation, create our own
2206 // queue of pending implicit instantiations that we will instantiate later,
2207 // while we're still within our own instantiation context.
2208 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2209 if (Recursive)
2210 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregor7caa6822009-07-24 20:34:43 +00002212 // Enter the scope of this instantiation. We don't use
2213 // PushDeclContext because we don't have a scope.
2214 DeclContext *PreviousContext = CurContext;
2215 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002217 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002218 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002219 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002220 CurContext = PreviousContext;
2221
2222 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002223 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2224 assert(MSInfo && "Missing member specialization information?");
2225 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2226 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002227 DeclGroupRef DG(Var);
2228 Consumer.HandleTopLevelDecl(DG);
2229 }
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Douglas Gregor7caa6822009-07-24 20:34:43 +00002231 if (Recursive) {
2232 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002233 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002234 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregor7caa6822009-07-24 20:34:43 +00002236 // Restore the set of pending implicit instantiations.
2237 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002238 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002239}
Douglas Gregor815215d2009-05-27 05:35:12 +00002240
Anders Carlsson09025312009-08-29 05:16:22 +00002241void
2242Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2243 const CXXConstructorDecl *Tmpl,
2244 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Anders Carlsson09025312009-08-29 05:16:22 +00002246 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002247 bool AnyErrors = false;
2248
Anders Carlsson09025312009-08-29 05:16:22 +00002249 // Instantiate all the initializers.
2250 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002251 InitsEnd = Tmpl->init_end();
2252 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002253 CXXBaseOrMemberInitializer *Init = *Inits;
2254
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002255 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002256 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002257 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002259 // Instantiate the initializer.
2260 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2261 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2262 AnyErrors = true;
2263 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002264 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002265
Anders Carlsson09025312009-08-29 05:16:22 +00002266 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002267 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002268 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002269 TemplateArgs,
2270 Init->getSourceLocation(),
2271 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002272 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002273 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002274 New->setInvalidDecl();
2275 continue;
2276 }
2277
John McCalla93c9342009-12-07 02:54:59 +00002278 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002279 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002280 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002281 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002282 Init->getRParenLoc(),
2283 New->getParent());
2284 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002285 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002287 // Is this an anonymous union?
2288 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002289 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2290 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002291 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002292 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2293 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002294 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002295
2296 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002297 NewArgs.size(),
2298 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002299 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002300 Init->getRParenLoc());
2301 }
2302
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002303 if (NewInit.isInvalid()) {
2304 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002305 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002306 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002307 // FIXME: It would be nice if ASTOwningVector had a release function.
2308 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Anders Carlsson09025312009-08-29 05:16:22 +00002310 NewInits.push_back((MemInitTy *)NewInit.get());
2311 }
2312 }
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Anders Carlsson09025312009-08-29 05:16:22 +00002314 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002315 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002316 /*FIXME: ColonLoc */
2317 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002318 NewInits.data(), NewInits.size(),
2319 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002320}
2321
John McCall52a575a2009-08-29 08:11:13 +00002322// TODO: this could be templated if the various decl types used the
2323// same method name.
2324static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2325 ClassTemplateDecl *Instance) {
2326 Pattern = Pattern->getCanonicalDecl();
2327
2328 do {
2329 Instance = Instance->getCanonicalDecl();
2330 if (Pattern == Instance) return true;
2331 Instance = Instance->getInstantiatedFromMemberTemplate();
2332 } while (Instance);
2333
2334 return false;
2335}
2336
Douglas Gregor0d696532009-09-28 06:34:35 +00002337static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2338 FunctionTemplateDecl *Instance) {
2339 Pattern = Pattern->getCanonicalDecl();
2340
2341 do {
2342 Instance = Instance->getCanonicalDecl();
2343 if (Pattern == Instance) return true;
2344 Instance = Instance->getInstantiatedFromMemberTemplate();
2345 } while (Instance);
2346
2347 return false;
2348}
2349
Douglas Gregored9c0f92009-10-29 00:04:11 +00002350static bool
2351isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2352 ClassTemplatePartialSpecializationDecl *Instance) {
2353 Pattern
2354 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2355 do {
2356 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2357 Instance->getCanonicalDecl());
2358 if (Pattern == Instance)
2359 return true;
2360 Instance = Instance->getInstantiatedFromMember();
2361 } while (Instance);
2362
2363 return false;
2364}
2365
John McCall52a575a2009-08-29 08:11:13 +00002366static bool isInstantiationOf(CXXRecordDecl *Pattern,
2367 CXXRecordDecl *Instance) {
2368 Pattern = Pattern->getCanonicalDecl();
2369
2370 do {
2371 Instance = Instance->getCanonicalDecl();
2372 if (Pattern == Instance) return true;
2373 Instance = Instance->getInstantiatedFromMemberClass();
2374 } while (Instance);
2375
2376 return false;
2377}
2378
2379static bool isInstantiationOf(FunctionDecl *Pattern,
2380 FunctionDecl *Instance) {
2381 Pattern = Pattern->getCanonicalDecl();
2382
2383 do {
2384 Instance = Instance->getCanonicalDecl();
2385 if (Pattern == Instance) return true;
2386 Instance = Instance->getInstantiatedFromMemberFunction();
2387 } while (Instance);
2388
2389 return false;
2390}
2391
2392static bool isInstantiationOf(EnumDecl *Pattern,
2393 EnumDecl *Instance) {
2394 Pattern = Pattern->getCanonicalDecl();
2395
2396 do {
2397 Instance = Instance->getCanonicalDecl();
2398 if (Pattern == Instance) return true;
2399 Instance = Instance->getInstantiatedFromMemberEnum();
2400 } while (Instance);
2401
2402 return false;
2403}
2404
John McCalled976492009-12-04 22:46:56 +00002405static bool isInstantiationOf(UsingShadowDecl *Pattern,
2406 UsingShadowDecl *Instance,
2407 ASTContext &C) {
2408 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2409}
2410
2411static bool isInstantiationOf(UsingDecl *Pattern,
2412 UsingDecl *Instance,
2413 ASTContext &C) {
2414 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2415}
2416
John McCall7ba107a2009-11-18 02:36:19 +00002417static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2418 UsingDecl *Instance,
2419 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002420 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002421}
2422
2423static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002424 UsingDecl *Instance,
2425 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002426 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002427}
2428
John McCall52a575a2009-08-29 08:11:13 +00002429static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2430 VarDecl *Instance) {
2431 assert(Instance->isStaticDataMember());
2432
2433 Pattern = Pattern->getCanonicalDecl();
2434
2435 do {
2436 Instance = Instance->getCanonicalDecl();
2437 if (Pattern == Instance) return true;
2438 Instance = Instance->getInstantiatedFromStaticDataMember();
2439 } while (Instance);
2440
2441 return false;
2442}
2443
John McCalled976492009-12-04 22:46:56 +00002444// Other is the prospective instantiation
2445// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002446static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002447 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002448 if (UnresolvedUsingTypenameDecl *UUD
2449 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2450 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2451 return isInstantiationOf(UUD, UD, Ctx);
2452 }
2453 }
2454
2455 if (UnresolvedUsingValueDecl *UUD
2456 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002457 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2458 return isInstantiationOf(UUD, UD, Ctx);
2459 }
2460 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002461
Anders Carlsson0d8df782009-08-29 19:37:28 +00002462 return false;
2463 }
Mike Stump1eb44332009-09-09 15:08:12 +00002464
John McCall52a575a2009-08-29 08:11:13 +00002465 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2466 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002467
John McCall52a575a2009-08-29 08:11:13 +00002468 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2469 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002470
John McCall52a575a2009-08-29 08:11:13 +00002471 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2472 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002473
Douglas Gregor7caa6822009-07-24 20:34:43 +00002474 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002475 if (Var->isStaticDataMember())
2476 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2477
2478 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2479 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002480
Douglas Gregor0d696532009-09-28 06:34:35 +00002481 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2482 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2483
Douglas Gregored9c0f92009-10-29 00:04:11 +00002484 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2485 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2486 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2487 PartialSpec);
2488
Anders Carlssond8b285f2009-09-01 04:26:58 +00002489 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2490 if (!Field->getDeclName()) {
2491 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002492 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002493 cast<FieldDecl>(D);
2494 }
2495 }
Mike Stump1eb44332009-09-09 15:08:12 +00002496
John McCalled976492009-12-04 22:46:56 +00002497 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2498 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2499
2500 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2501 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2502
Douglas Gregor815215d2009-05-27 05:35:12 +00002503 return D->getDeclName() && isa<NamedDecl>(Other) &&
2504 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2505}
2506
2507template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002508static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002509 NamedDecl *D,
2510 ForwardIterator first,
2511 ForwardIterator last) {
2512 for (; first != last; ++first)
2513 if (isInstantiationOf(Ctx, D, *first))
2514 return cast<NamedDecl>(*first);
2515
2516 return 0;
2517}
2518
John McCall02cace72009-08-28 07:59:38 +00002519/// \brief Finds the instantiation of the given declaration context
2520/// within the current instantiation.
2521///
2522/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002523DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002524 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002525 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002526 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002527 return cast_or_null<DeclContext>(ID);
2528 } else return DC;
2529}
2530
Douglas Gregored961e72009-05-27 17:54:46 +00002531/// \brief Find the instantiation of the given declaration within the
2532/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002533///
2534/// This routine is intended to be used when \p D is a declaration
2535/// referenced from within a template, that needs to mapped into the
2536/// corresponding declaration within an instantiation. For example,
2537/// given:
2538///
2539/// \code
2540/// template<typename T>
2541/// struct X {
2542/// enum Kind {
2543/// KnownValue = sizeof(T)
2544/// };
2545///
2546/// bool getKind() const { return KnownValue; }
2547/// };
2548///
2549/// template struct X<int>;
2550/// \endcode
2551///
2552/// In the instantiation of X<int>::getKind(), we need to map the
2553/// EnumConstantDecl for KnownValue (which refers to
2554/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002555/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2556/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002557NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002558 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002559 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002560 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002561 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002562 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002563 // D is a local of some kind. Look into the map of local
2564 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002565 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002566 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002567
Douglas Gregore95b4092009-09-16 18:34:49 +00002568 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2569 if (!Record->isDependentContext())
2570 return D;
2571
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002572 // If the RecordDecl is actually the injected-class-name or a
2573 // "templated" declaration for a class template, class template
2574 // partial specialization, or a member class of a class template,
2575 // substitute into the injected-class-name of the class template
2576 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002577 QualType T;
2578 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2579
2580 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002581 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002582 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2583 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002584 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002585
2586 // If we call SubstType with an InjectedClassNameType here we
2587 // can end up in an infinite loop.
2588 T = Context.getTypeDeclType(Record);
2589 assert(isa<InjectedClassNameType>(T) &&
2590 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002591 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002592 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002593
2594 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002595 // Substitute into the injected-class-name to get the type
2596 // corresponding to the instantiation we want, which may also be
2597 // the current instantiation (if we're in a template
2598 // definition). This substitution should never fail, since we
2599 // know we can instantiate the injected-class-name or we
2600 // wouldn't have gotten to the injected-class-name!
2601
2602 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2603 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002604 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2605 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2606
2607 if (!T->isDependentType()) {
2608 assert(T->isRecordType() && "Instantiation must produce a record type");
2609 return T->getAs<RecordType>()->getDecl();
2610 }
2611
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002612 // We are performing "partial" template instantiation to create
2613 // the member declarations for the members of a class template
2614 // specialization. Therefore, D is actually referring to something
2615 // in the current instantiation. Look through the current
2616 // context, which contains actual instantiations, to find the
2617 // instantiation of the "current instantiation" that D refers
2618 // to.
2619 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002620 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002621 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002622 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002623 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002624 if (isInstantiationOf(ClassTemplate,
2625 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002626 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002627
2628 if (!DC->isDependentContext())
2629 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002630 }
2631
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002632 // We're performing "instantiation" of a member of the current
2633 // instantiation while we are type-checking the
2634 // definition. Compute the declaration context and return that.
2635 assert(!SawNonDependentContext &&
2636 "No dependent context while instantiating record");
2637 DeclContext *DC = computeDeclContext(T);
2638 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002639 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002640 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002641 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002642
Douglas Gregore95b4092009-09-16 18:34:49 +00002643 // Fall through to deal with other dependent record types (e.g.,
2644 // anonymous unions in class templates).
2645 }
John McCall52a575a2009-08-29 08:11:13 +00002646
Douglas Gregore95b4092009-09-16 18:34:49 +00002647 if (!ParentDC->isDependentContext())
2648 return D;
2649
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002650 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002651 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002652 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Douglas Gregor815215d2009-05-27 05:35:12 +00002654 if (ParentDC != D->getDeclContext()) {
2655 // We performed some kind of instantiation in the parent context,
2656 // so now we need to look into the instantiated parent context to
2657 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002658
John McCall3cb0ebd2010-03-10 03:28:59 +00002659 // If our context used to be dependent, we may need to instantiate
2660 // it before performing lookup into that context.
2661 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002662 if (!Spec->isDependentContext()) {
2663 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002664 const RecordType *Tag = T->getAs<RecordType>();
2665 assert(Tag && "type of non-dependent record is not a RecordType");
2666 if (!Tag->isBeingDefined() &&
2667 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2668 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002669 }
2670 }
2671
Douglas Gregor815215d2009-05-27 05:35:12 +00002672 NamedDecl *Result = 0;
2673 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002674 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002675 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2676 } else {
2677 // Since we don't have a name for the entity we're looking for,
2678 // our only option is to walk through all of the declarations to
2679 // find that name. This will occur in a few cases:
2680 //
2681 // - anonymous struct/union within a template
2682 // - unnamed class/struct/union/enum within a template
2683 //
2684 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002685 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002686 ParentDC->decls_begin(),
2687 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002688 }
Mike Stump1eb44332009-09-09 15:08:12 +00002689
John McCall9f54ad42009-12-10 09:41:52 +00002690 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002691 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2692 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002693 && "Unable to find instantiation of declaration!");
2694
Douglas Gregor815215d2009-05-27 05:35:12 +00002695 D = Result;
2696 }
2697
Douglas Gregor815215d2009-05-27 05:35:12 +00002698 return D;
2699}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002700
Mike Stump1eb44332009-09-09 15:08:12 +00002701/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002702/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002703void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2704 while (!PendingLocalImplicitInstantiations.empty() ||
2705 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2706 PendingImplicitInstantiation Inst;
2707
2708 if (PendingLocalImplicitInstantiations.empty()) {
2709 Inst = PendingImplicitInstantiations.front();
2710 PendingImplicitInstantiations.pop_front();
2711 } else {
2712 Inst = PendingLocalImplicitInstantiations.front();
2713 PendingLocalImplicitInstantiations.pop_front();
2714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Douglas Gregor7caa6822009-07-24 20:34:43 +00002716 // Instantiate function definitions
2717 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002718 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002719 Function->getLocation(), *this,
2720 Context.getSourceManager(),
2721 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002723 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002724 continue;
2725 }
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Douglas Gregor7caa6822009-07-24 20:34:43 +00002727 // Instantiate static data member definitions.
2728 VarDecl *Var = cast<VarDecl>(Inst.first);
2729 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002730
Chandler Carruth291b4412010-02-13 10:17:50 +00002731 // Don't try to instantiate declarations if the most recent redeclaration
2732 // is invalid.
2733 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2734 continue;
2735
2736 // Check if the most recent declaration has changed the specialization kind
2737 // and removed the need for implicit instantiation.
2738 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2739 case TSK_Undeclared:
2740 assert(false && "Cannot instantitiate an undeclared specialization.");
2741 case TSK_ExplicitInstantiationDeclaration:
2742 case TSK_ExplicitInstantiationDefinition:
2743 case TSK_ExplicitSpecialization:
2744 continue; // No longer need implicit instantiation.
2745 case TSK_ImplicitInstantiation:
2746 break;
2747 }
2748
Mike Stump1eb44332009-09-09 15:08:12 +00002749 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002750 Var->getLocation(), *this,
2751 Context.getSourceManager(),
2752 "instantiating static data member "
2753 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Douglas Gregor7caa6822009-07-24 20:34:43 +00002755 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002756 }
2757}
John McCall0c01d182010-03-24 05:22:00 +00002758
2759void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2760 const MultiLevelTemplateArgumentList &TemplateArgs) {
2761 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2762 E = Pattern->ddiag_end(); I != E; ++I) {
2763 DependentDiagnostic *DD = *I;
2764
2765 switch (DD->getKind()) {
2766 case DependentDiagnostic::Access:
2767 HandleDependentAccessCheck(*DD, TemplateArgs);
2768 break;
2769 }
2770 }
2771}