blob: a853d91d042fb3460a887408cd42ec8b5fb0af89 [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.
John McCalld226f652010-08-21 09:40:31 +0000430 SemaRef.AddCXXDirectInitializerToDecl(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]);
John McCalld226f652010-08-21 09:40:31 +0000437 SemaRef.AddInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000438 SemaRef.Owned(Init),
439 false);
440 } else {
441 assert(InitArgs.size() == 0);
John McCalld226f652010-08-21 09:40:31 +0000442 SemaRef.ActOnUninitializedDecl(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())
John McCalld226f652010-08-21 09:40:31 +0000452 SemaRef.ActOnUninitializedDecl(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();
John McCalld226f652010-08-21 09:40:31 +0000596 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
597 move(InstantiatedAssertExpr),
598 move(Message));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000599}
600
601Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000602 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000603 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000604 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000606 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000607 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000608 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000609 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000610 Enum->startDefinition();
611
Douglas Gregor96084f12010-03-01 19:00:07 +0000612 if (D->getDeclContext()->isFunctionOrMethod())
613 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
614
John McCalld226f652010-08-21 09:40:31 +0000615 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000616
617 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000618 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
619 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000620 EC != ECEnd; ++EC) {
621 // The specified value for the enumerator.
622 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000623 if (Expr *UninstValue = EC->getInitExpr()) {
624 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000625 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000626 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000627
John McCallce3ff2b2009-08-25 22:02:44 +0000628 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000629 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000630
631 // Drop the initial value and continue.
632 bool isInvalid = false;
633 if (Value.isInvalid()) {
634 Value = SemaRef.Owned((Expr *)0);
635 isInvalid = true;
636 }
637
Mike Stump1eb44332009-09-09 15:08:12 +0000638 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000639 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
640 EC->getLocation(), EC->getIdentifier(),
641 move(Value));
642
643 if (isInvalid) {
644 if (EnumConst)
645 EnumConst->setInvalidDecl();
646 Enum->setInvalidDecl();
647 }
648
649 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000650 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000651 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000652 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000653 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000654
655 if (D->getDeclContext()->isFunctionOrMethod()) {
656 // If the enumeration is within a function or method, record the enum
657 // constant as a local.
658 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
659 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000660 }
661 }
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000663 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000664 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000665 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000666 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000667 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000668 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000669
670 return Enum;
671}
672
Douglas Gregor6477b692009-03-25 15:04:13 +0000673Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
674 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
675 return 0;
676}
677
John McCalle29ba202009-08-20 01:44:21 +0000678Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000679 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
680
Douglas Gregor550d9b22009-10-31 17:21:17 +0000681 // Create a local instantiation scope for this class template, which
682 // will contain the instantiations of the template parameters.
683 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000684 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000685 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000686 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000687 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000688
689 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000690
691 // Instantiate the qualifier. We have to do this first in case
692 // we're a friend declaration, because if we are then we need to put
693 // the new declaration in the appropriate context.
694 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
695 if (Qualifier) {
696 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
697 Pattern->getQualifierRange(),
698 TemplateArgs);
699 if (!Qualifier) return 0;
700 }
701
702 CXXRecordDecl *PrevDecl = 0;
703 ClassTemplateDecl *PrevClassTemplate = 0;
704
705 // If this isn't a friend, then it's a member template, in which
706 // case we just want to build the instantiation in the
707 // specialization. If it is a friend, we want to build it in
708 // the appropriate context.
709 DeclContext *DC = Owner;
710 if (isFriend) {
711 if (Qualifier) {
712 CXXScopeSpec SS;
713 SS.setScopeRep(Qualifier);
714 SS.setRange(Pattern->getQualifierRange());
715 DC = SemaRef.computeDeclContext(SS);
716 if (!DC) return 0;
717 } else {
718 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
719 Pattern->getDeclContext(),
720 TemplateArgs);
721 }
722
723 // Look for a previous declaration of the template in the owning
724 // context.
725 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
726 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
727 SemaRef.LookupQualifiedName(R, DC);
728
729 if (R.isSingleResult()) {
730 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
731 if (PrevClassTemplate)
732 PrevDecl = PrevClassTemplate->getTemplatedDecl();
733 }
734
735 if (!PrevClassTemplate && Qualifier) {
736 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000737 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
738 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000739 return 0;
740 }
741
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000742 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000743 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000744 bool Complain = true;
745
746 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
747 // template for struct std::tr1::__detail::_Map_base, where the
748 // template parameters of the friend declaration don't match the
749 // template parameters of the original declaration. In this one
750 // case, we don't complain about the ill-formed friend
751 // declaration.
752 if (isFriend && Pattern->getIdentifier() &&
753 Pattern->getIdentifier()->isStr("_Map_base") &&
754 DC->isNamespace() &&
755 cast<NamespaceDecl>(DC)->getIdentifier() &&
756 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
757 DeclContext *DCParent = DC->getParent();
758 if (DCParent->isNamespace() &&
759 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
760 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
761 DeclContext *DCParent2 = DCParent->getParent();
762 if (DCParent2->isNamespace() &&
763 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
764 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
765 DCParent2->getParent()->isTranslationUnit())
766 Complain = false;
767 }
768 }
769
John McCall93ba8572010-03-25 06:39:04 +0000770 TemplateParameterList *PrevParams
771 = PrevClassTemplate->getTemplateParameters();
772
773 // Make sure the parameter lists match.
774 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000775 Complain,
776 Sema::TPL_TemplateMatch)) {
777 if (Complain)
778 return 0;
779
780 AdoptedPreviousTemplateParams = true;
781 InstParams = PrevParams;
782 }
John McCall93ba8572010-03-25 06:39:04 +0000783
784 // Do some additional validation, then merge default arguments
785 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000786 if (!AdoptedPreviousTemplateParams &&
787 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000788 Sema::TPC_ClassTemplate))
789 return 0;
790 }
791 }
792
John McCalle29ba202009-08-20 01:44:21 +0000793 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000794 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000795 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000796 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000797 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000798
John McCall93ba8572010-03-25 06:39:04 +0000799 if (Qualifier)
800 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000801
John McCalle29ba202009-08-20 01:44:21 +0000802 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000803 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
804 D->getIdentifier(), InstParams, RecordInst,
805 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000806 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000807
John McCall93ba8572010-03-25 06:39:04 +0000808 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000809 if (PrevClassTemplate)
810 Inst->setAccess(PrevClassTemplate->getAccess());
811 else
812 Inst->setAccess(D->getAccess());
813
John McCall93ba8572010-03-25 06:39:04 +0000814 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
815 // TODO: do we want to track the instantiation progeny of this
816 // friend target decl?
817 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000818 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000819 Inst->setInstantiatedFromMemberTemplate(D);
820 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000821
822 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000823 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000824 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000825
Douglas Gregor259571e2009-10-30 22:42:42 +0000826 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000827 if (isFriend) {
828 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000829 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000830 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000831
John McCalle29ba202009-08-20 01:44:21 +0000832 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000833
Douglas Gregored9c0f92009-10-29 00:04:11 +0000834 // Instantiate all of the partial specializations of this member class
835 // template.
Douglas Gregordc60c1e2010-04-30 05:56:50 +0000836 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
837 D->getPartialSpecializations(PartialSpecs);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000838 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
839 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
840
John McCalle29ba202009-08-20 01:44:21 +0000841 return Inst;
842}
843
Douglas Gregord60e1052009-08-27 16:57:43 +0000844Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000845TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
846 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000847 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
848
849 // Lookup the already-instantiated declaration in the instantiation
850 // of the class template and return that.
851 DeclContext::lookup_result Found
852 = Owner->lookup(ClassTemplate->getDeclName());
853 if (Found.first == Found.second)
854 return 0;
855
856 ClassTemplateDecl *InstClassTemplate
857 = dyn_cast<ClassTemplateDecl>(*Found.first);
858 if (!InstClassTemplate)
859 return 0;
860
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +0000861 return InstClassTemplate->findPartialSpecInstantiatedFromMember(D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000862}
863
864Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000865TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000866 // Create a local instantiation scope for this function template, which
867 // will contain the instantiations of the template parameters and then get
868 // merged with the local instantiation scope for the function template
869 // itself.
870 Sema::LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000871
Douglas Gregord60e1052009-08-27 16:57:43 +0000872 TemplateParameterList *TempParams = D->getTemplateParameters();
873 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000874 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000875 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000876
Douglas Gregora735b202009-10-13 14:39:41 +0000877 FunctionDecl *Instantiated = 0;
878 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
879 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
880 InstParams));
881 else
882 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
883 D->getTemplatedDecl(),
884 InstParams));
885
886 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000887 return 0;
888
John McCall46460a62010-01-20 21:53:11 +0000889 Instantiated->setAccess(D->getAccess());
890
Mike Stump1eb44332009-09-09 15:08:12 +0000891 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000892 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000893 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000894 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000895 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000896 assert(InstTemplate &&
897 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000898
John McCallb1a56e72010-03-26 23:10:15 +0000899 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
900
John McCalle976ffe2009-12-14 23:19:40 +0000901 // Link the instantiation back to the pattern *unless* this is a
902 // non-definition friend declaration.
903 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000904 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000905 InstTemplate->setInstantiatedFromMemberTemplate(D);
906
John McCallb1a56e72010-03-26 23:10:15 +0000907 // Make declarations visible in the appropriate context.
908 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000909 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000910
Douglas Gregord60e1052009-08-27 16:57:43 +0000911 return InstTemplate;
912}
913
Douglas Gregord475b8d2009-03-25 21:17:03 +0000914Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
915 CXXRecordDecl *PrevDecl = 0;
916 if (D->isInjectedClassName())
917 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000918 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000919 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
920 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000921 TemplateArgs);
922 if (!Prev) return 0;
923 PrevDecl = cast<CXXRecordDecl>(Prev);
924 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000925
926 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000927 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000928 D->getLocation(), D->getIdentifier(),
929 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000930
931 // Substitute the nested name specifier, if any.
932 if (SubstQualifier(D, Record))
933 return 0;
934
Douglas Gregord475b8d2009-03-25 21:17:03 +0000935 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000936 // FIXME: Check against AS_none is an ugly hack to work around the issue that
937 // the tag decls introduced by friend class declarations don't have an access
938 // specifier. Remove once this area of the code gets sorted out.
939 if (D->getAccess() != AS_none)
940 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000941 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000942 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000943
John McCall02cace72009-08-28 07:59:38 +0000944 // If the original function was part of a friend declaration,
945 // inherit its namespace state.
946 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
947 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
948
Douglas Gregor9901c572010-05-21 00:31:19 +0000949 // Make sure that anonymous structs and unions are recorded.
950 if (D->isAnonymousStructOrUnion()) {
951 Record->setAnonymousStructOrUnion(true);
952 if (Record->getDeclContext()->getLookupContext()->isFunctionOrMethod())
953 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
954 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000955
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000956 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000957 return Record;
958}
959
John McCall02cace72009-08-28 07:59:38 +0000960/// Normal class members are of more specific types and therefore
961/// don't make it here. This function serves two purposes:
962/// 1) instantiating function templates
963/// 2) substituting friend declarations
964/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000965Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000966 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000967 // Check whether there is already a function template specialization for
968 // this declaration.
969 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
970 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000971 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000972 std::pair<const TemplateArgument *, unsigned> Innermost
973 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000975 FunctionDecl *SpecFunc
976 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
977 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregor127102b2009-06-29 20:59:39 +0000979 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000980 if (SpecFunc)
981 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
John McCallb0cb0222010-03-27 05:57:59 +0000984 bool isFriend;
985 if (FunctionTemplate)
986 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
987 else
988 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
989
Douglas Gregor79c22782010-01-16 20:21:20 +0000990 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000991 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000992 !(isa<Decl>(Owner) &&
993 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
994 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Douglas Gregore53060f2009-06-25 22:08:12 +0000996 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000997 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
998 TInfo = SubstFunctionType(D, Params);
999 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001000 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001001 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001002
John McCalld325daa2010-03-26 04:53:08 +00001003 NestedNameSpecifier *Qualifier = D->getQualifier();
1004 if (Qualifier) {
1005 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1006 D->getQualifierRange(),
1007 TemplateArgs);
1008 if (!Qualifier) return 0;
1009 }
1010
John McCall68b6b872010-02-06 01:50:47 +00001011 // If we're instantiating a local function declaration, put the result
1012 // in the owner; otherwise we need to find the instantiated context.
1013 DeclContext *DC;
1014 if (D->getDeclContext()->isFunctionOrMethod())
1015 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001016 else if (isFriend && Qualifier) {
1017 CXXScopeSpec SS;
1018 SS.setScopeRep(Qualifier);
1019 SS.setRange(D->getQualifierRange());
1020 DC = SemaRef.computeDeclContext(SS);
1021 if (!DC) return 0;
1022 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001023 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1024 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001025 }
John McCall68b6b872010-02-06 01:50:47 +00001026
John McCall02cace72009-08-28 07:59:38 +00001027 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001028 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001029 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001030 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001031 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001032
John McCalld325daa2010-03-26 04:53:08 +00001033 if (Qualifier)
1034 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001035
John McCallb1a56e72010-03-26 23:10:15 +00001036 DeclContext *LexicalDC = Owner;
1037 if (!isFriend && D->isOutOfLine()) {
1038 assert(D->getDeclContext()->isFileContext());
1039 LexicalDC = D->getDeclContext();
1040 }
1041
1042 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Douglas Gregore53060f2009-06-25 22:08:12 +00001044 // Attach the parameters
1045 for (unsigned P = 0; P < Params.size(); ++P)
1046 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001047 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001048
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001049 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001050 if (TemplateParams) {
1051 // Our resulting instantiation is actually a function template, since we
1052 // are substituting only the outer template parameters. For example, given
1053 //
1054 // template<typename T>
1055 // struct X {
1056 // template<typename U> friend void f(T, U);
1057 // };
1058 //
1059 // X<int> x;
1060 //
1061 // We are instantiating the friend function template "f" within X<int>,
1062 // which means substituting int for T, but leaving "f" as a friend function
1063 // template.
1064 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001065 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001066 Function->getLocation(),
1067 Function->getDeclName(),
1068 TemplateParams, Function);
1069 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001070
1071 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001072
1073 if (isFriend && D->isThisDeclarationADefinition()) {
1074 // TODO: should we remember this connection regardless of whether
1075 // the friend declaration provided a body?
1076 FunctionTemplate->setInstantiatedFromMemberTemplate(
1077 D->getDescribedFunctionTemplate());
1078 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001079 } else if (FunctionTemplate) {
1080 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001081 std::pair<const TemplateArgument *, unsigned> Innermost
1082 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001083 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001084 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1085 Innermost.first,
1086 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001087 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001088 } else if (isFriend && D->isThisDeclarationADefinition()) {
1089 // TODO: should we remember this connection regardless of whether
1090 // the friend declaration provided a body?
1091 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001092 }
Douglas Gregora735b202009-10-13 14:39:41 +00001093
Douglas Gregore53060f2009-06-25 22:08:12 +00001094 if (InitFunctionInstantiation(Function, D))
1095 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Douglas Gregore53060f2009-06-25 22:08:12 +00001097 bool Redeclaration = false;
1098 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001099 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001100
John McCall68263142009-11-18 22:49:29 +00001101 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1102 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1103
John McCallaf2094e2010-04-08 09:05:18 +00001104 if (DependentFunctionTemplateSpecializationInfo *Info
1105 = D->getDependentSpecializationInfo()) {
1106 assert(isFriend && "non-friend has dependent specialization info?");
1107
1108 // This needs to be set now for future sanity.
1109 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1110
1111 // Instantiate the explicit template arguments.
1112 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1113 Info->getRAngleLoc());
1114 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1115 TemplateArgumentLoc Loc;
1116 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1117 return 0;
1118
1119 ExplicitArgs.addArgument(Loc);
1120 }
1121
1122 // Map the candidate templates to their instantiations.
1123 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1124 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1125 Info->getTemplate(I),
1126 TemplateArgs);
1127 if (!Temp) return 0;
1128
1129 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1130 }
1131
1132 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1133 &ExplicitArgs,
1134 Previous))
1135 Function->setInvalidDecl();
1136
1137 isExplicitSpecialization = true;
1138
1139 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001140 // Look only into the namespace where the friend would be declared to
1141 // find a previous declaration. This is the innermost enclosing namespace,
1142 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001143 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001144
Douglas Gregora735b202009-10-13 14:39:41 +00001145 // In C++, the previous declaration we find might be a tag type
1146 // (class or enum). In this case, the new declaration will hide the
1147 // tag type. Note that this does does not apply if we're declaring a
1148 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001149 if (Previous.isSingleTagDecl())
1150 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001151 }
1152
John McCall9f54ad42009-12-10 09:41:52 +00001153 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001154 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001155 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001156
John McCall76d32642010-04-24 01:30:58 +00001157 NamedDecl *PrincipalDecl = (TemplateParams
1158 ? cast<NamedDecl>(FunctionTemplate)
1159 : Function);
1160
Douglas Gregora735b202009-10-13 14:39:41 +00001161 // If the original function was part of a friend declaration,
1162 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001163 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001164 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001165 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001166 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001167 else
Douglas Gregora735b202009-10-13 14:39:41 +00001168 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001169
1170 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1171 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregor238058c2010-05-18 05:45:02 +00001172
1173 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1174 D->isThisDeclarationADefinition()) {
1175 // Check for a function body.
1176 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001177 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001178 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1179 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1180 << Function->getDeclName();
1181 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1182 Function->setInvalidDecl();
1183 }
1184 // Check for redefinitions due to other instantiations of this or
1185 // a similar friend function.
1186 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1187 REnd = Function->redecls_end();
1188 R != REnd; ++R) {
1189 if (*R != Function &&
1190 ((*R)->getFriendObjectKind() != Decl::FOK_None)) {
1191 if (const FunctionDecl *RPattern
1192 = (*R)->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001193 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001194 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1195 << Function->getDeclName();
1196 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition);
1197 Function->setInvalidDecl();
1198 break;
1199 }
1200 }
1201 }
1202 }
1203
Douglas Gregora735b202009-10-13 14:39:41 +00001204 }
1205
John McCall76d32642010-04-24 01:30:58 +00001206 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1207 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1208 PrincipalDecl->setNonMemberOperator();
1209
Douglas Gregore53060f2009-06-25 22:08:12 +00001210 return Function;
1211}
1212
Douglas Gregord60e1052009-08-27 16:57:43 +00001213Decl *
1214TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1215 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001216 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1217 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001218 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001219 // We are creating a function template specialization from a function
1220 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001221 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001222 std::pair<const TemplateArgument *, unsigned> Innermost
1223 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001225 FunctionDecl *SpecFunc
1226 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1227 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregor6b906862009-08-21 00:16:32 +00001229 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001230 if (SpecFunc)
1231 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001232 }
1233
John McCallb0cb0222010-03-27 05:57:59 +00001234 bool isFriend;
1235 if (FunctionTemplate)
1236 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1237 else
1238 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1239
Douglas Gregor79c22782010-01-16 20:21:20 +00001240 bool MergeWithParentScope = (TemplateParams != 0) ||
1241 !(isa<Decl>(Owner) &&
1242 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1243 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001244
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001245 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001246 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1247 TInfo = SubstFunctionType(D, Params);
1248 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001249 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001250 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001251
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001252 // \brief If the type of this function is not *directly* a function
1253 // type, then we're instantiating the a function that was declared
1254 // via a typedef, e.g.,
1255 //
1256 // typedef int functype(int, int);
1257 // functype func;
1258 //
1259 // In this case, we'll just go instantiate the ParmVarDecls that we
1260 // synthesized in the method declaration.
1261 if (!isa<FunctionProtoType>(T)) {
1262 assert(!Params.size() && "Instantiating type could not yield parameters");
1263 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1264 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1265 TemplateArgs);
1266 if (!P)
1267 return 0;
1268
1269 Params.push_back(P);
1270 }
1271 }
1272
John McCallb0cb0222010-03-27 05:57:59 +00001273 NestedNameSpecifier *Qualifier = D->getQualifier();
1274 if (Qualifier) {
1275 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1276 D->getQualifierRange(),
1277 TemplateArgs);
1278 if (!Qualifier) return 0;
1279 }
1280
1281 DeclContext *DC = Owner;
1282 if (isFriend) {
1283 if (Qualifier) {
1284 CXXScopeSpec SS;
1285 SS.setScopeRep(Qualifier);
1286 SS.setRange(D->getQualifierRange());
1287 DC = SemaRef.computeDeclContext(SS);
1288 } else {
1289 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1290 D->getDeclContext(),
1291 TemplateArgs);
1292 }
1293 if (!DC) return 0;
1294 }
1295
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001296 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001297 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001298 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Abramo Bagnara25777432010-08-11 22:01:17 +00001300 DeclarationNameInfo NameInfo
1301 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001302 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001303 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001304 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001305 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001306 Constructor->isInlineSpecified(),
1307 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001308 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001309 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001310 NameInfo, T,
1311 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001312 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001313 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001314 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001315 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001316 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001317 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001318 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001319 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1320 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001321 D->isStatic(),
1322 D->getStorageClassAsWritten(),
1323 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001324 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001325
John McCallb0cb0222010-03-27 05:57:59 +00001326 if (Qualifier)
1327 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001328
Douglas Gregord60e1052009-08-27 16:57:43 +00001329 if (TemplateParams) {
1330 // Our resulting instantiation is actually a function template, since we
1331 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001332 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001333 // template<typename T>
1334 // struct X {
1335 // template<typename U> void f(T, U);
1336 // };
1337 //
1338 // X<int> x;
1339 //
1340 // We are instantiating the member template "f" within X<int>, which means
1341 // substituting int for T, but leaving "f" as a member function template.
1342 // Build the function template itself.
1343 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1344 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001345 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001346 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001347 if (isFriend) {
1348 FunctionTemplate->setLexicalDeclContext(Owner);
1349 FunctionTemplate->setObjectOfFriendDecl(true);
1350 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001351 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001352 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001353 } else if (FunctionTemplate) {
1354 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001355 std::pair<const TemplateArgument *, unsigned> Innermost
1356 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001357 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001358 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1359 Innermost.first,
1360 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001361 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001362 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001363 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001364 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001365 }
1366
Mike Stump1eb44332009-09-09 15:08:12 +00001367 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001368 // out-of-line, the instantiation will have the same lexical
1369 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001370 if (isFriend) {
1371 Method->setLexicalDeclContext(Owner);
1372 Method->setObjectOfFriendDecl(true);
1373 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001374 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Douglas Gregor5545e162009-03-24 00:38:23 +00001376 // Attach the parameters
1377 for (unsigned P = 0; P < Params.size(); ++P)
1378 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001379 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001380
1381 if (InitMethodInstantiation(Method, D))
1382 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001383
Abramo Bagnara25777432010-08-11 22:01:17 +00001384 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1385 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001386
John McCallb0cb0222010-03-27 05:57:59 +00001387 if (!FunctionTemplate || TemplateParams || isFriend) {
1388 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Douglas Gregordec06662009-08-21 18:42:58 +00001390 // In C++, the previous declaration we find might be a tag type
1391 // (class or enum). In this case, the new declaration will hide the
1392 // tag type. Note that this does does not apply if we're declaring a
1393 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001394 if (Previous.isSingleTagDecl())
1395 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001396 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001397
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001398 bool Redeclaration = false;
1399 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001400 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001401 /*FIXME:*/OverloadableAttrRequired);
1402
Douglas Gregor4ba31362009-12-01 17:24:26 +00001403 if (D->isPure())
1404 SemaRef.CheckPureMethod(Method, SourceRange());
1405
John McCall46460a62010-01-20 21:53:11 +00001406 Method->setAccess(D->getAccess());
1407
John McCallb0cb0222010-03-27 05:57:59 +00001408 if (FunctionTemplate) {
1409 // If there's a function template, let our caller handle it.
1410 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1411 // Don't hide a (potentially) valid declaration with an invalid one.
1412 } else {
1413 NamedDecl *DeclToAdd = (TemplateParams
1414 ? cast<NamedDecl>(FunctionTemplate)
1415 : Method);
1416 if (isFriend)
1417 Record->makeDeclVisibleInContext(DeclToAdd);
1418 else
1419 Owner->addDecl(DeclToAdd);
1420 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001421
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001422 return Method;
1423}
1424
Douglas Gregor615c5d42009-03-24 16:43:20 +00001425Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001426 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001427}
1428
Douglas Gregor03b2b072009-03-24 00:15:49 +00001429Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001430 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001431}
1432
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001433Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001434 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001435}
1436
Douglas Gregor6477b692009-03-25 15:04:13 +00001437ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001438 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001439}
1440
John McCalle29ba202009-08-20 01:44:21 +00001441Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1442 TemplateTypeParmDecl *D) {
1443 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001444 const Type* T = D->getTypeForDecl();
1445 assert(T->isTemplateTypeParmType());
1446 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCalle29ba202009-08-20 01:44:21 +00001448 TemplateTypeParmDecl *Inst =
1449 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregorefed5c82010-06-16 15:23:05 +00001450 TTPT->getDepth() - 1, TTPT->getIndex(),
1451 TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001452 D->wasDeclaredWithTypename(),
1453 D->isParameterPack());
1454
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001455 if (D->hasDefaultArgument())
1456 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001457
Douglas Gregor550d9b22009-10-31 17:21:17 +00001458 // Introduce this template parameter's instantiation into the instantiation
1459 // scope.
1460 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1461
John McCalle29ba202009-08-20 01:44:21 +00001462 return Inst;
1463}
1464
Douglas Gregor33642df2009-10-23 23:25:44 +00001465Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1466 NonTypeTemplateParmDecl *D) {
1467 // Substitute into the type of the non-type template parameter.
1468 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001469 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001470 if (DI) {
1471 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1472 D->getDeclName());
1473 if (DI) T = DI->getType();
1474 } else {
1475 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1476 D->getDeclName());
1477 DI = 0;
1478 }
1479 if (T.isNull())
1480 return 0;
1481
1482 // Check that this type is acceptable for a non-type template parameter.
1483 bool Invalid = false;
1484 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1485 if (T.isNull()) {
1486 T = SemaRef.Context.IntTy;
1487 Invalid = true;
1488 }
1489
1490 NonTypeTemplateParmDecl *Param
1491 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1492 D->getDepth() - 1, D->getPosition(),
1493 D->getIdentifier(), T, DI);
1494 if (Invalid)
1495 Param->setInvalidDecl();
1496
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001497 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001498
1499 // Introduce this template parameter's instantiation into the instantiation
1500 // scope.
1501 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001502 return Param;
1503}
1504
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001505Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001506TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1507 TemplateTemplateParmDecl *D) {
1508 // Instantiate the template parameter list of the template template parameter.
1509 TemplateParameterList *TempParams = D->getTemplateParameters();
1510 TemplateParameterList *InstParams;
1511 {
1512 // Perform the actual substitution of template parameters within a new,
1513 // local instantiation scope.
1514 Sema::LocalInstantiationScope Scope(SemaRef);
1515 InstParams = SubstTemplateParams(TempParams);
1516 if (!InstParams)
1517 return NULL;
1518 }
1519
1520 // Build the template template parameter.
1521 TemplateTemplateParmDecl *Param
1522 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1523 D->getDepth() - 1, D->getPosition(),
1524 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001525 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001526
Douglas Gregor9106ef72009-11-11 16:58:32 +00001527 // Introduce this template parameter's instantiation into the instantiation
1528 // scope.
1529 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1530
1531 return Param;
1532}
1533
Douglas Gregor48c32a72009-11-17 06:07:40 +00001534Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1535 // Using directives are never dependent, so they require no explicit
1536
1537 UsingDirectiveDecl *Inst
1538 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1539 D->getNamespaceKeyLocation(),
1540 D->getQualifierRange(), D->getQualifier(),
1541 D->getIdentLocation(),
1542 D->getNominatedNamespace(),
1543 D->getCommonAncestor());
1544 Owner->addDecl(Inst);
1545 return Inst;
1546}
1547
John McCalled976492009-12-04 22:46:56 +00001548Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1549 // The nested name specifier is non-dependent, so no transformation
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001550 // is required. The same holds for the name info.
1551 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001552
John McCall9f54ad42009-12-10 09:41:52 +00001553 // We only need to do redeclaration lookups if we're in a class
1554 // scope (in fact, it's not really even possible in non-class
1555 // scopes).
1556 bool CheckRedeclaration = Owner->isRecord();
1557
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001558 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1559 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001560
John McCalled976492009-12-04 22:46:56 +00001561 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001562 D->getNestedNameRange(),
1563 D->getUsingLocation(),
1564 D->getTargetNestedNameDecl(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001565 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001566 D->isTypeName());
1567
1568 CXXScopeSpec SS;
1569 SS.setScopeRep(D->getTargetNestedNameDecl());
1570 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001571
1572 if (CheckRedeclaration) {
1573 Prev.setHideTags(false);
1574 SemaRef.LookupQualifiedName(Prev, Owner);
1575
1576 // Check for invalid redeclarations.
1577 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1578 D->isTypeName(), SS,
1579 D->getLocation(), Prev))
1580 NewUD->setInvalidDecl();
1581
1582 }
1583
1584 if (!NewUD->isInvalidDecl() &&
1585 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001586 D->getLocation()))
1587 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001588
John McCalled976492009-12-04 22:46:56 +00001589 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1590 NewUD->setAccess(D->getAccess());
1591 Owner->addDecl(NewUD);
1592
John McCall9f54ad42009-12-10 09:41:52 +00001593 // Don't process the shadow decls for an invalid decl.
1594 if (NewUD->isInvalidDecl())
1595 return NewUD;
1596
John McCall323c3102009-12-22 22:26:37 +00001597 bool isFunctionScope = Owner->isFunctionOrMethod();
1598
John McCall9f54ad42009-12-10 09:41:52 +00001599 // Process the shadow decls.
1600 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1601 I != E; ++I) {
1602 UsingShadowDecl *Shadow = *I;
1603 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001604 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1605 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001606 TemplateArgs));
1607
1608 if (CheckRedeclaration &&
1609 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1610 continue;
1611
1612 UsingShadowDecl *InstShadow
1613 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1614 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001615
1616 if (isFunctionScope)
1617 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001618 }
John McCalled976492009-12-04 22:46:56 +00001619
1620 return NewUD;
1621}
1622
1623Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001624 // Ignore these; we handle them in bulk when processing the UsingDecl.
1625 return 0;
John McCalled976492009-12-04 22:46:56 +00001626}
1627
John McCall7ba107a2009-11-18 02:36:19 +00001628Decl * TemplateDeclInstantiator
1629 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001630 NestedNameSpecifier *NNS =
1631 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1632 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001633 TemplateArgs);
1634 if (!NNS)
1635 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001637 CXXScopeSpec SS;
1638 SS.setRange(D->getTargetNestedNameRange());
1639 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001641 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1642 // Hence, no tranformation is required for it.
1643 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001644 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001645 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001646 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001647 /*instantiation*/ true,
1648 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001649 if (UD)
John McCalled976492009-12-04 22:46:56 +00001650 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1651
John McCall7ba107a2009-11-18 02:36:19 +00001652 return UD;
1653}
1654
1655Decl * TemplateDeclInstantiator
1656 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1657 NestedNameSpecifier *NNS =
1658 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1659 D->getTargetNestedNameRange(),
1660 TemplateArgs);
1661 if (!NNS)
1662 return 0;
1663
1664 CXXScopeSpec SS;
1665 SS.setRange(D->getTargetNestedNameRange());
1666 SS.setScopeRep(NNS);
1667
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001668 DeclarationNameInfo NameInfo
1669 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1670
John McCall7ba107a2009-11-18 02:36:19 +00001671 NamedDecl *UD =
1672 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001673 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001674 /*instantiation*/ true,
1675 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001676 if (UD)
John McCalled976492009-12-04 22:46:56 +00001677 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1678
Anders Carlsson0d8df782009-08-29 19:37:28 +00001679 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001680}
1681
John McCallce3ff2b2009-08-25 22:02:44 +00001682Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001683 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001684 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001685 if (D->isInvalidDecl())
1686 return 0;
1687
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001688 return Instantiator.Visit(D);
1689}
1690
John McCalle29ba202009-08-20 01:44:21 +00001691/// \brief Instantiates a nested template parameter list in the current
1692/// instantiation context.
1693///
1694/// \param L The parameter list to instantiate
1695///
1696/// \returns NULL if there was an error
1697TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001698TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001699 // Get errors for all the parameters before bailing out.
1700 bool Invalid = false;
1701
1702 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001703 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001704 ParamVector Params;
1705 Params.reserve(N);
1706 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1707 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001708 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001709 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001710 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001711 }
1712
1713 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001714 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001715 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001716
1717 TemplateParameterList *InstL
1718 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1719 L->getLAngleLoc(), &Params.front(), N,
1720 L->getRAngleLoc());
1721 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001722}
John McCalle29ba202009-08-20 01:44:21 +00001723
Douglas Gregored9c0f92009-10-29 00:04:11 +00001724/// \brief Instantiate the declaration of a class template partial
1725/// specialization.
1726///
1727/// \param ClassTemplate the (instantiated) class template that is partially
1728// specialized by the instantiation of \p PartialSpec.
1729///
1730/// \param PartialSpec the (uninstantiated) class template partial
1731/// specialization that we are instantiating.
1732///
1733/// \returns true if there was an error, false otherwise.
1734bool
1735TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1736 ClassTemplateDecl *ClassTemplate,
1737 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001738 // Create a local instantiation scope for this class template partial
1739 // specialization, which will contain the instantiations of the template
1740 // parameters.
1741 Sema::LocalInstantiationScope Scope(SemaRef);
1742
Douglas Gregored9c0f92009-10-29 00:04:11 +00001743 // Substitute into the template parameters of the class template partial
1744 // specialization.
1745 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1746 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1747 if (!InstParams)
1748 return true;
1749
1750 // Substitute into the template arguments of the class template partial
1751 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001752 const TemplateArgumentLoc *PartialSpecTemplateArgs
1753 = PartialSpec->getTemplateArgsAsWritten();
1754 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1755
John McCalld5532b62009-11-23 01:53:49 +00001756 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001757 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001758 TemplateArgumentLoc Loc;
1759 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001760 return true;
John McCalld5532b62009-11-23 01:53:49 +00001761 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001762 }
1763
1764
1765 // Check that the template argument list is well-formed for this
1766 // class template.
1767 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1768 InstTemplateArgs.size());
1769 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1770 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001771 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001772 false,
1773 Converted))
1774 return true;
1775
1776 // Figure out where to insert this class template partial specialization
1777 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001778 void *InsertPos = 0;
1779 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001780 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
1781 Converted.flatSize(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001782
1783 // Build the canonical type that describes the converted template
1784 // arguments of the class template partial specialization.
1785 QualType CanonType
1786 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1787 Converted.getFlatArguments(),
1788 Converted.flatSize());
1789
1790 // Build the fully-sugared type for this class template
1791 // specialization as the user wrote in the specialization
1792 // itself. This means that we'll pretty-print the type retrieved
1793 // from the specialization's declaration the way that the user
1794 // actually wrote the specialization, rather than formatting the
1795 // name based on the "canonical" representation used to store the
1796 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001797 TypeSourceInfo *WrittenTy
1798 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1799 TemplateName(ClassTemplate),
1800 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001801 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001802 CanonType);
1803
1804 if (PrevDecl) {
1805 // We've already seen a partial specialization with the same template
1806 // parameters and template arguments. This can happen, for example, when
1807 // substituting the outer template arguments ends up causing two
1808 // class template partial specializations of a member class template
1809 // to have identical forms, e.g.,
1810 //
1811 // template<typename T, typename U>
1812 // struct Outer {
1813 // template<typename X, typename Y> struct Inner;
1814 // template<typename Y> struct Inner<T, Y>;
1815 // template<typename Y> struct Inner<U, Y>;
1816 // };
1817 //
1818 // Outer<int, int> outer; // error: the partial specializations of Inner
1819 // // have the same signature.
1820 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1821 << WrittenTy;
1822 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1823 << SemaRef.Context.getTypeDeclType(PrevDecl);
1824 return true;
1825 }
1826
1827
1828 // Create the class template partial specialization declaration.
1829 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001830 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1831 PartialSpec->getTagKind(),
1832 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001833 PartialSpec->getLocation(),
1834 InstParams,
1835 ClassTemplate,
1836 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001837 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001838 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001839 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001840 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001841 // Substitute the nested name specifier, if any.
1842 if (SubstQualifier(PartialSpec, InstPartialSpec))
1843 return 0;
1844
Douglas Gregored9c0f92009-10-29 00:04:11 +00001845 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001846 InstPartialSpec->setTypeAsWritten(WrittenTy);
1847
Douglas Gregored9c0f92009-10-29 00:04:11 +00001848 // Add this partial specialization to the set of class template partial
1849 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001850 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001851 return false;
1852}
1853
John McCall21ef0fa2010-03-11 09:03:00 +00001854TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001855TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001856 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001857 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1858 assert(OldTInfo && "substituting function without type source info");
1859 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001860 TypeSourceInfo *NewTInfo
1861 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1862 D->getTypeSpecStartLoc(),
1863 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001864 if (!NewTInfo)
1865 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001866
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001867 if (NewTInfo != OldTInfo) {
1868 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001869 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001870 if (FunctionProtoTypeLoc *OldProtoLoc
1871 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1872 TypeLoc NewTL = NewTInfo->getTypeLoc();
1873 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1874 assert(NewProtoLoc && "Missing prototype?");
1875 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1876 // FIXME: Variadic templates will break this.
1877 Params.push_back(NewProtoLoc->getArg(i));
1878 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001879 OldProtoLoc->getArg(i),
1880 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001881 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001882 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001883 } else {
1884 // The function type itself was not dependent and therefore no
1885 // substitution occurred. However, we still need to instantiate
1886 // the function parameters themselves.
1887 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001888 if (FunctionProtoTypeLoc *OldProtoLoc
1889 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1890 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1891 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1892 if (!Parm)
1893 return 0;
1894 Params.push_back(Parm);
1895 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001896 }
1897 }
John McCall21ef0fa2010-03-11 09:03:00 +00001898 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001899}
1900
Mike Stump1eb44332009-09-09 15:08:12 +00001901/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001902/// declaration (New) from the corresponding fields of its template (Tmpl).
1903///
1904/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001905bool
1906TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001907 FunctionDecl *Tmpl) {
1908 if (Tmpl->isDeleted())
1909 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Douglas Gregorcca9e962009-07-01 22:01:06 +00001911 // If we are performing substituting explicitly-specified template arguments
1912 // or deduced template arguments into a function template and we reach this
1913 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001914 // to keeping the new function template specialization. We therefore
1915 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001916 // into a template instantiation for this specific function template
1917 // specialization, which is not a SFINAE context, so that we diagnose any
1918 // further errors in the declaration itself.
1919 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1920 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1921 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1922 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001923 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001924 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001925 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001926 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001927 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001928 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1929 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001930 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001931 }
1932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001934 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1935 assert(Proto && "Function template without prototype?");
1936
1937 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1938 Proto->getNoReturnAttr()) {
1939 // The function has an exception specification or a "noreturn"
1940 // attribute. Substitute into each of the exception types.
1941 llvm::SmallVector<QualType, 4> Exceptions;
1942 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1943 // FIXME: Poor location information!
1944 QualType T
1945 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1946 New->getLocation(), New->getDeclName());
1947 if (T.isNull() ||
1948 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1949 continue;
1950
1951 Exceptions.push_back(T);
1952 }
1953
1954 // Rebuild the function type
1955
1956 const FunctionProtoType *NewProto
1957 = New->getType()->getAs<FunctionProtoType>();
1958 assert(NewProto && "Template instantiation without function prototype?");
1959 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1960 NewProto->arg_type_begin(),
1961 NewProto->getNumArgs(),
1962 NewProto->isVariadic(),
1963 NewProto->getTypeQuals(),
1964 Proto->hasExceptionSpec(),
1965 Proto->hasAnyExceptionSpec(),
1966 Exceptions.size(),
1967 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001968 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001969 }
1970
John McCall1d8d1cc2010-08-01 02:01:53 +00001971 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00001972
Douglas Gregore53060f2009-06-25 22:08:12 +00001973 return false;
1974}
1975
Douglas Gregor5545e162009-03-24 00:38:23 +00001976/// \brief Initializes common fields of an instantiated method
1977/// declaration (New) from the corresponding fields of its template
1978/// (Tmpl).
1979///
1980/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001981bool
1982TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001983 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001984 if (InitFunctionInstantiation(New, Tmpl))
1985 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Douglas Gregor5545e162009-03-24 00:38:23 +00001987 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1988 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001989 if (Tmpl->isVirtualAsWritten())
1990 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001991
1992 // FIXME: attributes
1993 // FIXME: New needs a pointer to Tmpl
1994 return false;
1995}
Douglas Gregora58861f2009-05-13 20:28:22 +00001996
1997/// \brief Instantiate the definition of the given function from its
1998/// template.
1999///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002000/// \param PointOfInstantiation the point at which the instantiation was
2001/// required. Note that this is not precisely a "point of instantiation"
2002/// for the function, but it's close.
2003///
Douglas Gregora58861f2009-05-13 20:28:22 +00002004/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002005/// function template specialization or member function of a class template
2006/// specialization.
2007///
2008/// \param Recursive if true, recursively instantiates any functions that
2009/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002010///
2011/// \param DefinitionRequired if true, then we are performing an explicit
2012/// instantiation where the body of the function is required. Complain if
2013/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002014void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002015 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002016 bool Recursive,
2017 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002018 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002019 return;
2020
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002021 // Never instantiate an explicit specialization.
2022 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2023 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002024
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002025 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002026 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002027 Stmt *Pattern = 0;
2028 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002029 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002030
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002031 if (!Pattern) {
2032 if (DefinitionRequired) {
2033 if (Function->getPrimaryTemplate())
2034 Diag(PointOfInstantiation,
2035 diag::err_explicit_instantiation_undefined_func_template)
2036 << Function->getPrimaryTemplate();
2037 else
2038 Diag(PointOfInstantiation,
2039 diag::err_explicit_instantiation_undefined_member)
2040 << 1 << Function->getDeclName() << Function->getDeclContext();
2041
2042 if (PatternDecl)
2043 Diag(PatternDecl->getLocation(),
2044 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002045 Function->setInvalidDecl();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002046 }
2047
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002048 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002049 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002050
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002051 // C++0x [temp.explicit]p9:
2052 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002053 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002054 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002055 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002056 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002057 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002058 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002060 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2061 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002062 return;
2063
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002064 // If we're performing recursive template instantiation, create our own
2065 // queue of pending implicit instantiations that we will instantiate later,
2066 // while we're still within our own instantiation context.
2067 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2068 if (Recursive)
2069 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Douglas Gregor9679caf2010-05-12 17:27:19 +00002071 EnterExpressionEvaluationContext EvalContext(*this,
2072 Action::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002073 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002074
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002075 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002076 // recorded, unless we're actually a member function within a local
2077 // class, in which case we need to merge our results with the parent
2078 // scope (of the enclosing function).
2079 bool MergeWithParentScope = false;
2080 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2081 MergeWithParentScope = Rec->isLocalClass();
2082
2083 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002085 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002086 // instantiation scope, and set the parameter names to those used
2087 // in the template.
2088 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2089 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2090 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2091 FunctionParam->setDeclName(PatternParam->getDeclName());
2092 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2093 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002094
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002095 // Enter the scope of this instantiation. We don't use
2096 // PushDeclContext because we don't have a scope.
2097 DeclContext *PreviousContext = CurContext;
2098 CurContext = Function;
2099
Mike Stump1eb44332009-09-09 15:08:12 +00002100 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002101 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002102
2103 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002104 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002105 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2106 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2107 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002108 }
2109
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002110 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002111 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002112
Douglas Gregor52604ab2009-09-11 21:19:12 +00002113 if (Body.isInvalid())
2114 Function->setInvalidDecl();
2115
John McCalld226f652010-08-21 09:40:31 +00002116 ActOnFinishFunctionBody(Function, move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002117 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002118
John McCall0c01d182010-03-24 05:22:00 +00002119 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2120
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002121 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002122
2123 DeclGroupRef DG(Function);
2124 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Douglas Gregor60406be2010-01-16 22:29:39 +00002126 // This class may have local implicit instantiations that need to be
2127 // instantiation within this scope.
2128 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2129 Scope.Exit();
2130
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002131 if (Recursive) {
2132 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002133 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002134 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002136 // Restore the set of pending implicit instantiations.
2137 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2138 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002139}
2140
2141/// \brief Instantiate the definition of the given variable from its
2142/// template.
2143///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002144/// \param PointOfInstantiation the point at which the instantiation was
2145/// required. Note that this is not precisely a "point of instantiation"
2146/// for the function, but it's close.
2147///
2148/// \param Var the already-instantiated declaration of a static member
2149/// variable of a class template specialization.
2150///
2151/// \param Recursive if true, recursively instantiates any functions that
2152/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002153///
2154/// \param DefinitionRequired if true, then we are performing an explicit
2155/// instantiation where an out-of-line definition of the member variable
2156/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002157void Sema::InstantiateStaticDataMemberDefinition(
2158 SourceLocation PointOfInstantiation,
2159 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002160 bool Recursive,
2161 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002162 if (Var->isInvalidDecl())
2163 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Douglas Gregor7caa6822009-07-24 20:34:43 +00002165 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002166 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002167 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002168 assert(Def->isStaticDataMember() && "Not a static data member?");
2169 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Douglas Gregor0d035142009-10-27 18:42:08 +00002171 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002172 // We did not find an out-of-line definition of this static data member,
2173 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002174 // instantiate this definition (or provide a specialization for it) in
2175 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002176 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002177 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002178 Diag(PointOfInstantiation,
2179 diag::err_explicit_instantiation_undefined_member)
2180 << 2 << Var->getDeclName() << Var->getDeclContext();
2181 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2182 }
2183
Douglas Gregor7caa6822009-07-24 20:34:43 +00002184 return;
2185 }
2186
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002187 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002188 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002189 return;
2190
2191 // C++0x [temp.explicit]p9:
2192 // Except for inline functions, other explicit instantiation declarations
2193 // have the effect of suppressing the implicit instantiation of the entity
2194 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002195 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002196 == TSK_ExplicitInstantiationDeclaration)
2197 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Douglas Gregor7caa6822009-07-24 20:34:43 +00002199 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2200 if (Inst)
2201 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Douglas Gregor7caa6822009-07-24 20:34:43 +00002203 // If we're performing recursive template instantiation, create our own
2204 // queue of pending implicit instantiations that we will instantiate later,
2205 // while we're still within our own instantiation context.
2206 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2207 if (Recursive)
2208 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Douglas Gregor7caa6822009-07-24 20:34:43 +00002210 // Enter the scope of this instantiation. We don't use
2211 // PushDeclContext because we don't have a scope.
2212 DeclContext *PreviousContext = CurContext;
2213 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002215 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002216 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002217 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002218 CurContext = PreviousContext;
2219
2220 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002221 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2222 assert(MSInfo && "Missing member specialization information?");
2223 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2224 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002225 DeclGroupRef DG(Var);
2226 Consumer.HandleTopLevelDecl(DG);
2227 }
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Douglas Gregor7caa6822009-07-24 20:34:43 +00002229 if (Recursive) {
2230 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002231 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002232 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Douglas Gregor7caa6822009-07-24 20:34:43 +00002234 // Restore the set of pending implicit instantiations.
2235 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002236 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002237}
Douglas Gregor815215d2009-05-27 05:35:12 +00002238
Anders Carlsson09025312009-08-29 05:16:22 +00002239void
2240Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2241 const CXXConstructorDecl *Tmpl,
2242 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Anders Carlsson09025312009-08-29 05:16:22 +00002244 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002245 bool AnyErrors = false;
2246
Anders Carlsson09025312009-08-29 05:16:22 +00002247 // Instantiate all the initializers.
2248 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002249 InitsEnd = Tmpl->init_end();
2250 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002251 CXXBaseOrMemberInitializer *Init = *Inits;
2252
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002253 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002254 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002255 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002257 // Instantiate the initializer.
2258 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2259 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2260 AnyErrors = true;
2261 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002262 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002263
Anders Carlsson09025312009-08-29 05:16:22 +00002264 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002265 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002266 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002267 TemplateArgs,
2268 Init->getSourceLocation(),
2269 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002270 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002271 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002272 New->setInvalidDecl();
2273 continue;
2274 }
2275
John McCalla93c9342009-12-07 02:54:59 +00002276 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002277 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002278 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002279 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002280 Init->getRParenLoc(),
2281 New->getParent());
2282 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002283 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002285 // Is this an anonymous union?
2286 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002287 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2288 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002289 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002290 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2291 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002292 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002293
2294 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002295 NewArgs.size(),
2296 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002297 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002298 Init->getRParenLoc());
2299 }
2300
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002301 if (NewInit.isInvalid()) {
2302 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002303 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002304 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002305 // FIXME: It would be nice if ASTOwningVector had a release function.
2306 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Anders Carlsson09025312009-08-29 05:16:22 +00002308 NewInits.push_back((MemInitTy *)NewInit.get());
2309 }
2310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Anders Carlsson09025312009-08-29 05:16:22 +00002312 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002313 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002314 /*FIXME: ColonLoc */
2315 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002316 NewInits.data(), NewInits.size(),
2317 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002318}
2319
John McCall52a575a2009-08-29 08:11:13 +00002320// TODO: this could be templated if the various decl types used the
2321// same method name.
2322static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2323 ClassTemplateDecl *Instance) {
2324 Pattern = Pattern->getCanonicalDecl();
2325
2326 do {
2327 Instance = Instance->getCanonicalDecl();
2328 if (Pattern == Instance) return true;
2329 Instance = Instance->getInstantiatedFromMemberTemplate();
2330 } while (Instance);
2331
2332 return false;
2333}
2334
Douglas Gregor0d696532009-09-28 06:34:35 +00002335static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2336 FunctionTemplateDecl *Instance) {
2337 Pattern = Pattern->getCanonicalDecl();
2338
2339 do {
2340 Instance = Instance->getCanonicalDecl();
2341 if (Pattern == Instance) return true;
2342 Instance = Instance->getInstantiatedFromMemberTemplate();
2343 } while (Instance);
2344
2345 return false;
2346}
2347
Douglas Gregored9c0f92009-10-29 00:04:11 +00002348static bool
2349isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2350 ClassTemplatePartialSpecializationDecl *Instance) {
2351 Pattern
2352 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2353 do {
2354 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2355 Instance->getCanonicalDecl());
2356 if (Pattern == Instance)
2357 return true;
2358 Instance = Instance->getInstantiatedFromMember();
2359 } while (Instance);
2360
2361 return false;
2362}
2363
John McCall52a575a2009-08-29 08:11:13 +00002364static bool isInstantiationOf(CXXRecordDecl *Pattern,
2365 CXXRecordDecl *Instance) {
2366 Pattern = Pattern->getCanonicalDecl();
2367
2368 do {
2369 Instance = Instance->getCanonicalDecl();
2370 if (Pattern == Instance) return true;
2371 Instance = Instance->getInstantiatedFromMemberClass();
2372 } while (Instance);
2373
2374 return false;
2375}
2376
2377static bool isInstantiationOf(FunctionDecl *Pattern,
2378 FunctionDecl *Instance) {
2379 Pattern = Pattern->getCanonicalDecl();
2380
2381 do {
2382 Instance = Instance->getCanonicalDecl();
2383 if (Pattern == Instance) return true;
2384 Instance = Instance->getInstantiatedFromMemberFunction();
2385 } while (Instance);
2386
2387 return false;
2388}
2389
2390static bool isInstantiationOf(EnumDecl *Pattern,
2391 EnumDecl *Instance) {
2392 Pattern = Pattern->getCanonicalDecl();
2393
2394 do {
2395 Instance = Instance->getCanonicalDecl();
2396 if (Pattern == Instance) return true;
2397 Instance = Instance->getInstantiatedFromMemberEnum();
2398 } while (Instance);
2399
2400 return false;
2401}
2402
John McCalled976492009-12-04 22:46:56 +00002403static bool isInstantiationOf(UsingShadowDecl *Pattern,
2404 UsingShadowDecl *Instance,
2405 ASTContext &C) {
2406 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2407}
2408
2409static bool isInstantiationOf(UsingDecl *Pattern,
2410 UsingDecl *Instance,
2411 ASTContext &C) {
2412 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2413}
2414
John McCall7ba107a2009-11-18 02:36:19 +00002415static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2416 UsingDecl *Instance,
2417 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002418 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002419}
2420
2421static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002422 UsingDecl *Instance,
2423 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002424 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002425}
2426
John McCall52a575a2009-08-29 08:11:13 +00002427static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2428 VarDecl *Instance) {
2429 assert(Instance->isStaticDataMember());
2430
2431 Pattern = Pattern->getCanonicalDecl();
2432
2433 do {
2434 Instance = Instance->getCanonicalDecl();
2435 if (Pattern == Instance) return true;
2436 Instance = Instance->getInstantiatedFromStaticDataMember();
2437 } while (Instance);
2438
2439 return false;
2440}
2441
John McCalled976492009-12-04 22:46:56 +00002442// Other is the prospective instantiation
2443// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002444static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002445 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002446 if (UnresolvedUsingTypenameDecl *UUD
2447 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2448 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2449 return isInstantiationOf(UUD, UD, Ctx);
2450 }
2451 }
2452
2453 if (UnresolvedUsingValueDecl *UUD
2454 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002455 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2456 return isInstantiationOf(UUD, UD, Ctx);
2457 }
2458 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002459
Anders Carlsson0d8df782009-08-29 19:37:28 +00002460 return false;
2461 }
Mike Stump1eb44332009-09-09 15:08:12 +00002462
John McCall52a575a2009-08-29 08:11:13 +00002463 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2464 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002465
John McCall52a575a2009-08-29 08:11:13 +00002466 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2467 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002468
John McCall52a575a2009-08-29 08:11:13 +00002469 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2470 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002471
Douglas Gregor7caa6822009-07-24 20:34:43 +00002472 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002473 if (Var->isStaticDataMember())
2474 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2475
2476 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2477 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002478
Douglas Gregor0d696532009-09-28 06:34:35 +00002479 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2480 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2481
Douglas Gregored9c0f92009-10-29 00:04:11 +00002482 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2483 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2484 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2485 PartialSpec);
2486
Anders Carlssond8b285f2009-09-01 04:26:58 +00002487 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2488 if (!Field->getDeclName()) {
2489 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002490 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002491 cast<FieldDecl>(D);
2492 }
2493 }
Mike Stump1eb44332009-09-09 15:08:12 +00002494
John McCalled976492009-12-04 22:46:56 +00002495 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2496 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2497
2498 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2499 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2500
Douglas Gregor815215d2009-05-27 05:35:12 +00002501 return D->getDeclName() && isa<NamedDecl>(Other) &&
2502 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2503}
2504
2505template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002506static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002507 NamedDecl *D,
2508 ForwardIterator first,
2509 ForwardIterator last) {
2510 for (; first != last; ++first)
2511 if (isInstantiationOf(Ctx, D, *first))
2512 return cast<NamedDecl>(*first);
2513
2514 return 0;
2515}
2516
John McCall02cace72009-08-28 07:59:38 +00002517/// \brief Finds the instantiation of the given declaration context
2518/// within the current instantiation.
2519///
2520/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002521DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002522 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002523 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002524 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002525 return cast_or_null<DeclContext>(ID);
2526 } else return DC;
2527}
2528
Douglas Gregored961e72009-05-27 17:54:46 +00002529/// \brief Find the instantiation of the given declaration within the
2530/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002531///
2532/// This routine is intended to be used when \p D is a declaration
2533/// referenced from within a template, that needs to mapped into the
2534/// corresponding declaration within an instantiation. For example,
2535/// given:
2536///
2537/// \code
2538/// template<typename T>
2539/// struct X {
2540/// enum Kind {
2541/// KnownValue = sizeof(T)
2542/// };
2543///
2544/// bool getKind() const { return KnownValue; }
2545/// };
2546///
2547/// template struct X<int>;
2548/// \endcode
2549///
2550/// In the instantiation of X<int>::getKind(), we need to map the
2551/// EnumConstantDecl for KnownValue (which refers to
2552/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002553/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2554/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002555NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002556 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002557 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002558 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002559 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002560 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002561 // D is a local of some kind. Look into the map of local
2562 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002563 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002564 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002565
Douglas Gregore95b4092009-09-16 18:34:49 +00002566 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2567 if (!Record->isDependentContext())
2568 return D;
2569
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002570 // If the RecordDecl is actually the injected-class-name or a
2571 // "templated" declaration for a class template, class template
2572 // partial specialization, or a member class of a class template,
2573 // substitute into the injected-class-name of the class template
2574 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002575 QualType T;
2576 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2577
2578 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002579 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002580 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2581 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002582 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002583
2584 // If we call SubstType with an InjectedClassNameType here we
2585 // can end up in an infinite loop.
2586 T = Context.getTypeDeclType(Record);
2587 assert(isa<InjectedClassNameType>(T) &&
2588 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002589 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002590 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002591
2592 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002593 // Substitute into the injected-class-name to get the type
2594 // corresponding to the instantiation we want, which may also be
2595 // the current instantiation (if we're in a template
2596 // definition). This substitution should never fail, since we
2597 // know we can instantiate the injected-class-name or we
2598 // wouldn't have gotten to the injected-class-name!
2599
2600 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2601 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002602 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2603 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2604
2605 if (!T->isDependentType()) {
2606 assert(T->isRecordType() && "Instantiation must produce a record type");
2607 return T->getAs<RecordType>()->getDecl();
2608 }
2609
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002610 // We are performing "partial" template instantiation to create
2611 // the member declarations for the members of a class template
2612 // specialization. Therefore, D is actually referring to something
2613 // in the current instantiation. Look through the current
2614 // context, which contains actual instantiations, to find the
2615 // instantiation of the "current instantiation" that D refers
2616 // to.
2617 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002618 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002619 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002620 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002621 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002622 if (isInstantiationOf(ClassTemplate,
2623 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002624 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002625
2626 if (!DC->isDependentContext())
2627 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002628 }
2629
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002630 // We're performing "instantiation" of a member of the current
2631 // instantiation while we are type-checking the
2632 // definition. Compute the declaration context and return that.
2633 assert(!SawNonDependentContext &&
2634 "No dependent context while instantiating record");
2635 DeclContext *DC = computeDeclContext(T);
2636 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002637 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002638 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002639 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002640
Douglas Gregore95b4092009-09-16 18:34:49 +00002641 // Fall through to deal with other dependent record types (e.g.,
2642 // anonymous unions in class templates).
2643 }
John McCall52a575a2009-08-29 08:11:13 +00002644
Douglas Gregore95b4092009-09-16 18:34:49 +00002645 if (!ParentDC->isDependentContext())
2646 return D;
2647
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002648 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002649 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002650 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Douglas Gregor815215d2009-05-27 05:35:12 +00002652 if (ParentDC != D->getDeclContext()) {
2653 // We performed some kind of instantiation in the parent context,
2654 // so now we need to look into the instantiated parent context to
2655 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002656
John McCall3cb0ebd2010-03-10 03:28:59 +00002657 // If our context used to be dependent, we may need to instantiate
2658 // it before performing lookup into that context.
2659 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002660 if (!Spec->isDependentContext()) {
2661 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002662 const RecordType *Tag = T->getAs<RecordType>();
2663 assert(Tag && "type of non-dependent record is not a RecordType");
2664 if (!Tag->isBeingDefined() &&
2665 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2666 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002667 }
2668 }
2669
Douglas Gregor815215d2009-05-27 05:35:12 +00002670 NamedDecl *Result = 0;
2671 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002672 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002673 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2674 } else {
2675 // Since we don't have a name for the entity we're looking for,
2676 // our only option is to walk through all of the declarations to
2677 // find that name. This will occur in a few cases:
2678 //
2679 // - anonymous struct/union within a template
2680 // - unnamed class/struct/union/enum within a template
2681 //
2682 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002683 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002684 ParentDC->decls_begin(),
2685 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002686 }
Mike Stump1eb44332009-09-09 15:08:12 +00002687
John McCall9f54ad42009-12-10 09:41:52 +00002688 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002689 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2690 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002691 && "Unable to find instantiation of declaration!");
2692
Douglas Gregor815215d2009-05-27 05:35:12 +00002693 D = Result;
2694 }
2695
Douglas Gregor815215d2009-05-27 05:35:12 +00002696 return D;
2697}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002698
Mike Stump1eb44332009-09-09 15:08:12 +00002699/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002700/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002701void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2702 while (!PendingLocalImplicitInstantiations.empty() ||
2703 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2704 PendingImplicitInstantiation Inst;
2705
2706 if (PendingLocalImplicitInstantiations.empty()) {
2707 Inst = PendingImplicitInstantiations.front();
2708 PendingImplicitInstantiations.pop_front();
2709 } else {
2710 Inst = PendingLocalImplicitInstantiations.front();
2711 PendingLocalImplicitInstantiations.pop_front();
2712 }
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Douglas Gregor7caa6822009-07-24 20:34:43 +00002714 // Instantiate function definitions
2715 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCalld226f652010-08-21 09:40:31 +00002716 PrettyStackTraceActionsDecl CrashInfo(Function,
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002717 Function->getLocation(), *this,
2718 Context.getSourceManager(),
2719 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002720
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002721 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002722 continue;
2723 }
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Douglas Gregor7caa6822009-07-24 20:34:43 +00002725 // Instantiate static data member definitions.
2726 VarDecl *Var = cast<VarDecl>(Inst.first);
2727 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002728
Chandler Carruth291b4412010-02-13 10:17:50 +00002729 // Don't try to instantiate declarations if the most recent redeclaration
2730 // is invalid.
2731 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2732 continue;
2733
2734 // Check if the most recent declaration has changed the specialization kind
2735 // and removed the need for implicit instantiation.
2736 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2737 case TSK_Undeclared:
2738 assert(false && "Cannot instantitiate an undeclared specialization.");
2739 case TSK_ExplicitInstantiationDeclaration:
2740 case TSK_ExplicitInstantiationDefinition:
2741 case TSK_ExplicitSpecialization:
2742 continue; // No longer need implicit instantiation.
2743 case TSK_ImplicitInstantiation:
2744 break;
2745 }
2746
John McCalld226f652010-08-21 09:40:31 +00002747 PrettyStackTraceActionsDecl CrashInfo(Var, Var->getLocation(), *this,
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002748 Context.getSourceManager(),
2749 "instantiating static data member "
2750 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Douglas Gregor7caa6822009-07-24 20:34:43 +00002752 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002753 }
2754}
John McCall0c01d182010-03-24 05:22:00 +00002755
2756void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2757 const MultiLevelTemplateArgumentList &TemplateArgs) {
2758 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2759 E = Pattern->ddiag_end(); I != E; ++I) {
2760 DependentDiagnostic *DD = *I;
2761
2762 switch (DD->getKind()) {
2763 case DependentDiagnostic::Access:
2764 HandleDependentAccessCheck(*DD, TemplateArgs);
2765 break;
2766 }
2767 }
2768}