blob: 54c509544f7b5d061a9d5ca7ccd42a4509b879ff [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//===----------------------------------------------------------------------===/
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallf312b1e2010-08-26 23:41:50 +000014#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000020#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000022#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025
26using namespace clang;
27
John McCallb6217662010-03-15 10:12:16 +000028bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
30 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
31 if (!OldQual) return false;
32
33 SourceRange QualRange = OldDecl->getQualifierRange();
34
35 NestedNameSpecifier *NewQual
36 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
37 if (!NewQual)
38 return true;
39
40 NewDecl->setQualifierInfo(NewQual, QualRange);
41 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
46 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
47 if (!OldQual) return false;
48
49 SourceRange QualRange = OldDecl->getQualifierRange();
50
51 NestedNameSpecifier *NewQual
52 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
53 if (!NewQual)
54 return true;
55
56 NewDecl->setQualifierInfo(NewQual, QualRange);
57 return false;
58}
59
Chandler Carruth4ced79f2010-06-25 03:22:07 +000060// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +000061void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
62 Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +000063 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
64 i != e; ++i) {
65 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +000066 // FIXME: This should be generalized to more than just the AlignedAttr.
67 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +000068 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +000069 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +000070 EnterExpressionEvaluationContext Unevaluated(*this,
John McCallf312b1e2010-08-26 23:41:50 +000071 Sema::Unevaluated);
Chandler Carruth4ced79f2010-06-25 03:22:07 +000072
Sean Huntcf807c42010-08-18 23:23:40 +000073 if (Aligned->isAlignmentExpr()) {
John McCall60d7b3a2010-08-24 06:29:42 +000074 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Nick Lewycky7663f392010-11-20 01:29:55 +000075 TemplateArgs);
Sean Huntcf807c42010-08-18 23:23:40 +000076 if (!Result.isInvalid())
77 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
78 }
79 else {
80 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
Nick Lewycky7663f392010-11-20 01:29:55 +000081 TemplateArgs,
82 Aligned->getLocation(),
83 DeclarationName());
Sean Huntcf807c42010-08-18 23:23:40 +000084 if (Result)
85 AddAlignedAttr(Aligned->getLocation(), New, Result);
86 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +000087 continue;
88 }
89 }
90
Anders Carlssond8fe2d52009-11-07 06:07:58 +000091 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +000092 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +000093 New->addAttr(NewAttr);
94 }
95}
96
Douglas Gregor4f722be2009-03-25 15:45:12 +000097Decl *
98TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
99 assert(false && "Translation units cannot be instantiated");
100 return D;
101}
102
103Decl *
104TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
105 assert(false && "Namespaces cannot be instantiated");
106 return D;
107}
108
John McCall3dbd3d52010-02-16 06:53:13 +0000109Decl *
110TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
111 NamespaceAliasDecl *Inst
112 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
113 D->getNamespaceLoc(),
114 D->getAliasLoc(),
115 D->getNamespace()->getIdentifier(),
116 D->getQualifierRange(),
117 D->getQualifier(),
118 D->getTargetNameLoc(),
119 D->getNamespace());
120 Owner->addDecl(Inst);
121 return Inst;
122}
123
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000124Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
125 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000126 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000127 if (DI->getType()->isDependentType() ||
128 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000129 DI = SemaRef.SubstType(DI, TemplateArgs,
130 D->getLocation(), D->getDeclName());
131 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000132 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000133 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000134 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000135 } else {
136 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000137 }
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000139 // Create the new typedef
140 TypedefDecl *Typedef
141 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000142 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000143 if (Invalid)
144 Typedef->setInvalidDecl();
145
Douglas Gregord57a38e2010-04-23 16:25:07 +0000146 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
147 TagDecl *TD = TT->getDecl();
148
149 // If the TagDecl that the TypedefDecl points to is an anonymous decl
150 // keep track of the TypedefDecl.
151 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
152 TD->setTypedefForAnonDecl(Typedef);
153 }
154
John McCall5126fd02009-12-30 00:31:22 +0000155 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000156 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
157 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000158 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
159 }
160
John McCall1d8d1cc2010-08-01 02:01:53 +0000161 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000162
John McCall46460a62010-01-20 21:53:11 +0000163 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000164 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000166 return Typedef;
167}
168
Douglas Gregor6eef5192009-12-14 19:27:10 +0000169/// \brief Instantiate the arguments provided as part of initialization.
170///
171/// \returns true if an error occurred, false otherwise.
172static bool InstantiateInitializationArguments(Sema &SemaRef,
173 Expr **Args, unsigned NumArgs,
174 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallca0408f2010-08-23 06:44:23 +0000175 ASTOwningVector<Expr*> &InitArgs) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000176 for (unsigned I = 0; I != NumArgs; ++I) {
177 // When we hit the first defaulted argument, break out of the loop:
178 // we don't pass those default arguments on.
179 if (Args[I]->isDefaultArgument())
180 break;
181
John McCall60d7b3a2010-08-24 06:29:42 +0000182 ExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000183 if (Arg.isInvalid())
184 return true;
185
Douglas Gregor6eef5192009-12-14 19:27:10 +0000186 InitArgs.push_back(Arg.release());
Douglas Gregor6eef5192009-12-14 19:27:10 +0000187 }
188
189 return false;
190}
191
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000192/// \brief Instantiate an initializer, breaking it into separate
193/// initialization arguments.
194///
195/// \param S The semantic analysis object.
196///
197/// \param Init The initializer to instantiate.
198///
199/// \param TemplateArgs Template arguments to be substituted into the
200/// initializer.
201///
202/// \param NewArgs Will be filled in with the instantiation arguments.
203///
204/// \returns true if an error occurred, false otherwise
205static bool InstantiateInitializer(Sema &S, Expr *Init,
206 const MultiLevelTemplateArgumentList &TemplateArgs,
207 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000208 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000209 SourceLocation &RParenLoc) {
210 NewArgs.clear();
211 LParenLoc = SourceLocation();
212 RParenLoc = SourceLocation();
213
214 if (!Init)
215 return false;
216
John McCall4765fa02010-12-06 08:20:24 +0000217 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000218 Init = ExprTemp->getSubExpr();
219
220 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
221 Init = Binder->getSubExpr();
222
223 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
224 Init = ICE->getSubExprAsWritten();
225
226 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
227 LParenLoc = ParenList->getLParenLoc();
228 RParenLoc = ParenList->getRParenLoc();
229 return InstantiateInitializationArguments(S, ParenList->getExprs(),
230 ParenList->getNumExprs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000231 TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000232 }
233
234 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000235 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
236 if (InstantiateInitializationArguments(S,
237 Construct->getArgs(),
238 Construct->getNumArgs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000239 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000240 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000241
Douglas Gregor28329e52010-03-24 21:22:47 +0000242 // FIXME: Fake locations!
243 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000244 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000245 return false;
246 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000247 }
248
John McCall60d7b3a2010-08-24 06:29:42 +0000249 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000250 if (Result.isInvalid())
251 return true;
252
253 NewArgs.push_back(Result.takeAs<Expr>());
254 return false;
255}
256
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000257Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000258 // If this is the variable for an anonymous struct or union,
259 // instantiate the anonymous struct/union type first.
260 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
261 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
262 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
263 return 0;
264
John McCallce3ff2b2009-08-25 22:02:44 +0000265 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000266 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000267 TemplateArgs,
268 D->getTypeSpecStartLoc(),
269 D->getDeclName());
270 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000271 return 0;
272
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000273 if (DI->getType()->isFunctionType()) {
274 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
275 << D->isStaticDataMember() << DI->getType();
276 return 0;
277 }
278
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000279 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000280 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
281 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000282 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000283 D->getStorageClass(),
284 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000285 Var->setThreadSpecified(D->isThreadSpecified());
286 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000287
John McCallb6217662010-03-15 10:12:16 +0000288 // Substitute the nested name specifier, if any.
289 if (SubstQualifier(D, Var))
290 return 0;
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000293 // out-of-line, the instantiation will have the same lexical
294 // context (which will be a namespace scope) as the template.
295 if (D->isOutOfLine())
296 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000297
John McCall46460a62010-01-20 21:53:11 +0000298 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000299
300 if (!D->isStaticDataMember())
301 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000302
Mike Stump390b4cc2009-05-16 07:39:55 +0000303 // FIXME: In theory, we could have a previous declaration for variables that
304 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000305 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000306 // FIXME: having to fake up a LookupResult is dumb.
307 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000308 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000309 if (D->isStaticDataMember())
310 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000311 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregor7caa6822009-07-24 20:34:43 +0000313 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000314 if (!D->isStaticDataMember())
315 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000316 Owner->makeDeclVisibleInContext(Var);
317 } else {
318 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000319 if (Owner->isFunctionOrMethod())
320 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000321 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000322 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000323
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000324 // Link instantiations of static data members back to the template from
325 // which they were instantiated.
326 if (Var->isStaticDataMember())
327 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000328 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000329
Douglas Gregor60c93c92010-02-09 07:26:29 +0000330 if (Var->getAnyInitializer()) {
331 // We already have an initializer in the class.
332 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000333 if (Var->isStaticDataMember() && !D->isOutOfLine())
334 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
335 else
336 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
337
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000338 // Instantiate the initializer.
339 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000340 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000341 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000342 InitArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000343 // Attach the initializer to the declaration.
344 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000345 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000346 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000347 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000348 move_arg(InitArgs),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000349 RParenLoc);
350 } else if (InitArgs.size() == 1) {
John McCall9ae2f072010-08-23 23:25:46 +0000351 Expr *Init = InitArgs.take()[0];
352 SemaRef.AddInitializerToDecl(Var, Init, false);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000353 } else {
354 assert(InitArgs.size() == 0);
John McCalld226f652010-08-21 09:40:31 +0000355 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000356 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000357 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000358 // FIXME: Not too happy about invalidating the declaration
359 // because of a bogus initializer.
360 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000361 }
362
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000363 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000364 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000365 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000366
Douglas Gregor5764f612010-05-08 23:05:03 +0000367 // Diagnose unused local variables.
368 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
369 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000370
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000371 return Var;
372}
373
Abramo Bagnara6206d532010-06-05 05:09:32 +0000374Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
375 AccessSpecDecl* AD
376 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
377 D->getAccessSpecifierLoc(), D->getColonLoc());
378 Owner->addHiddenDecl(AD);
379 return AD;
380}
381
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000382Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
383 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000384 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000385 if (DI->getType()->isDependentType() ||
386 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000387 DI = SemaRef.SubstType(DI, TemplateArgs,
388 D->getLocation(), D->getDeclName());
389 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000390 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000391 Invalid = true;
392 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000393 // C++ [temp.arg.type]p3:
394 // If a declaration acquires a function type through a type
395 // dependent on a template-parameter and this causes a
396 // declaration that does not use the syntactic form of a
397 // function declarator to have function type, the program is
398 // ill-formed.
399 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000400 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000401 Invalid = true;
402 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000403 } else {
404 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000405 }
406
407 Expr *BitWidth = D->getBitWidth();
408 if (Invalid)
409 BitWidth = 0;
410 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000411 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000412 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
John McCall60d7b3a2010-08-24 06:29:42 +0000414 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000415 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000416 if (InstantiatedBitWidth.isInvalid()) {
417 Invalid = true;
418 BitWidth = 0;
419 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000420 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000421 }
422
John McCall07fb6be2009-10-22 23:33:21 +0000423 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
424 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000425 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000426 D->getLocation(),
427 D->isMutable(),
428 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000429 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 D->getAccess(),
431 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000432 if (!Field) {
433 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000434 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436
John McCall1d8d1cc2010-08-01 02:01:53 +0000437 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000438
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000439 if (Invalid)
440 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000442 if (!Field->getDeclName()) {
443 // Keep track of where this decl came from.
444 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000445 }
446 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
447 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000448 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000449 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000452 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000453 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000454 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455
456 return Field;
457}
458
Francois Pichet87c2e122010-11-21 06:08:52 +0000459Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
460 NamedDecl **NamedChain =
461 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
462
463 int i = 0;
464 for (IndirectFieldDecl::chain_iterator PI =
465 D->chain_begin(), PE = D->chain_end();
466 PI != PE; ++PI)
467 NamedChain[i++] = (SemaRef.FindInstantiatedDecl(D->getLocation(),
468 *PI, TemplateArgs));
469
Francois Pichet40e17752010-12-09 10:07:54 +0000470 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000471 IndirectFieldDecl* IndirectField
472 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000473 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000474 NamedChain, D->getChainingSize());
475
476
477 IndirectField->setImplicit(D->isImplicit());
478 IndirectField->setAccess(D->getAccess());
479 Owner->addDecl(IndirectField);
480 return IndirectField;
481}
482
John McCall02cace72009-08-28 07:59:38 +0000483Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000484 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000485 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000486 if (TypeSourceInfo *Ty = D->getFriendType()) {
487 TypeSourceInfo *InstTy =
488 SemaRef.SubstType(Ty, TemplateArgs,
489 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000490 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000491 return 0;
John McCall02cace72009-08-28 07:59:38 +0000492
Douglas Gregor06245bf2010-04-07 17:57:12 +0000493 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
494 if (!FD)
495 return 0;
496
497 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000498 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 Owner->addDecl(FD);
500 return FD;
501 }
502
503 NamedDecl *ND = D->getFriendDecl();
504 assert(ND && "friend decl must be a decl or a type!");
505
John McCallaf2094e2010-04-08 09:05:18 +0000506 // All of the Visit implementations for the various potential friend
507 // declarations have to be carefully written to work for friend
508 // objects, with the most important detail being that the target
509 // decl should almost certainly not be placed in Owner.
510 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000511 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
John McCall02cace72009-08-28 07:59:38 +0000513 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000514 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
515 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000516 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000517 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000518 Owner->addDecl(FD);
519 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000520}
521
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000522Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
523 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregorac7610d2009-06-22 20:57:11 +0000525 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000526 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000527
John McCall60d7b3a2010-08-24 06:29:42 +0000528 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000529 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000530 if (InstantiatedAssertExpr.isInvalid())
531 return 0;
532
John McCall60d7b3a2010-08-24 06:29:42 +0000533 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000534 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000535 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000536 InstantiatedAssertExpr.get(),
537 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000538}
539
540Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000541 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000542 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000543 D->getTagKeywordLoc(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000544 /*PrevDecl=*/0, D->isScoped(),
545 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000546 if (D->isFixed()) {
547 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
548 // If we have type source information for the underlying type, it means it
549 // has been explicitly set by the user. Perform substitution on it before
550 // moving on.
551 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
552 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
553 TemplateArgs,
554 UnderlyingLoc,
555 DeclarationName()));
556
557 if (!Enum->getIntegerTypeSourceInfo())
558 Enum->setIntegerType(SemaRef.Context.IntTy);
559 }
560 else {
561 assert(!D->getIntegerType()->isDependentType()
562 && "Dependent type without type source info");
563 Enum->setIntegerType(D->getIntegerType());
564 }
565 }
566
John McCall5b629aa2010-10-22 23:36:17 +0000567 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
568
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000569 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000570 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000571 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000572 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000573 Enum->startDefinition();
574
Douglas Gregor96084f12010-03-01 19:00:07 +0000575 if (D->getDeclContext()->isFunctionOrMethod())
576 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
577
John McCalld226f652010-08-21 09:40:31 +0000578 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000579
580 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000581 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
582 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000583 EC != ECEnd; ++EC) {
584 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000585 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000586 if (Expr *UninstValue = EC->getInitExpr()) {
587 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000588 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000589 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000590
John McCallce3ff2b2009-08-25 22:02:44 +0000591 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000592 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000593
594 // Drop the initial value and continue.
595 bool isInvalid = false;
596 if (Value.isInvalid()) {
597 Value = SemaRef.Owned((Expr *)0);
598 isInvalid = true;
599 }
600
Mike Stump1eb44332009-09-09 15:08:12 +0000601 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000602 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
603 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000604 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605
606 if (isInvalid) {
607 if (EnumConst)
608 EnumConst->setInvalidDecl();
609 Enum->setInvalidDecl();
610 }
611
612 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000613 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
614
John McCall3b85ecf2010-01-23 22:37:59 +0000615 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000616 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000617 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000618 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000619
620 if (D->getDeclContext()->isFunctionOrMethod()) {
621 // If the enumeration is within a function or method, record the enum
622 // constant as a local.
623 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
624 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000625 }
626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000628 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000629 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000630 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000631 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000632 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000633 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000634
635 return Enum;
636}
637
Douglas Gregor6477b692009-03-25 15:04:13 +0000638Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
639 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
640 return 0;
641}
642
John McCalle29ba202009-08-20 01:44:21 +0000643Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000644 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
645
Douglas Gregor550d9b22009-10-31 17:21:17 +0000646 // Create a local instantiation scope for this class template, which
647 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000648 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000649 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000650 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000651 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000652 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000653
654 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000655
656 // Instantiate the qualifier. We have to do this first in case
657 // we're a friend declaration, because if we are then we need to put
658 // the new declaration in the appropriate context.
659 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
660 if (Qualifier) {
661 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
662 Pattern->getQualifierRange(),
663 TemplateArgs);
664 if (!Qualifier) return 0;
665 }
666
667 CXXRecordDecl *PrevDecl = 0;
668 ClassTemplateDecl *PrevClassTemplate = 0;
669
Nick Lewycky37574f52010-11-08 23:29:42 +0000670 if (!isFriend && Pattern->getPreviousDeclaration()) {
671 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
672 if (Found.first != Found.second) {
673 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
674 if (PrevClassTemplate)
675 PrevDecl = PrevClassTemplate->getTemplatedDecl();
676 }
677 }
678
John McCall93ba8572010-03-25 06:39:04 +0000679 // If this isn't a friend, then it's a member template, in which
680 // case we just want to build the instantiation in the
681 // specialization. If it is a friend, we want to build it in
682 // the appropriate context.
683 DeclContext *DC = Owner;
684 if (isFriend) {
685 if (Qualifier) {
686 CXXScopeSpec SS;
687 SS.setScopeRep(Qualifier);
688 SS.setRange(Pattern->getQualifierRange());
689 DC = SemaRef.computeDeclContext(SS);
690 if (!DC) return 0;
691 } else {
692 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
693 Pattern->getDeclContext(),
694 TemplateArgs);
695 }
696
697 // Look for a previous declaration of the template in the owning
698 // context.
699 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
700 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
701 SemaRef.LookupQualifiedName(R, DC);
702
703 if (R.isSingleResult()) {
704 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
705 if (PrevClassTemplate)
706 PrevDecl = PrevClassTemplate->getTemplatedDecl();
707 }
708
709 if (!PrevClassTemplate && Qualifier) {
710 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000711 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
712 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000713 return 0;
714 }
715
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000716 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000717 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000718 bool Complain = true;
719
720 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
721 // template for struct std::tr1::__detail::_Map_base, where the
722 // template parameters of the friend declaration don't match the
723 // template parameters of the original declaration. In this one
724 // case, we don't complain about the ill-formed friend
725 // declaration.
726 if (isFriend && Pattern->getIdentifier() &&
727 Pattern->getIdentifier()->isStr("_Map_base") &&
728 DC->isNamespace() &&
729 cast<NamespaceDecl>(DC)->getIdentifier() &&
730 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
731 DeclContext *DCParent = DC->getParent();
732 if (DCParent->isNamespace() &&
733 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
734 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
735 DeclContext *DCParent2 = DCParent->getParent();
736 if (DCParent2->isNamespace() &&
737 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
738 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
739 DCParent2->getParent()->isTranslationUnit())
740 Complain = false;
741 }
742 }
743
John McCall93ba8572010-03-25 06:39:04 +0000744 TemplateParameterList *PrevParams
745 = PrevClassTemplate->getTemplateParameters();
746
747 // Make sure the parameter lists match.
748 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000749 Complain,
750 Sema::TPL_TemplateMatch)) {
751 if (Complain)
752 return 0;
753
754 AdoptedPreviousTemplateParams = true;
755 InstParams = PrevParams;
756 }
John McCall93ba8572010-03-25 06:39:04 +0000757
758 // Do some additional validation, then merge default arguments
759 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000760 if (!AdoptedPreviousTemplateParams &&
761 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000762 Sema::TPC_ClassTemplate))
763 return 0;
764 }
765 }
766
John McCalle29ba202009-08-20 01:44:21 +0000767 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000768 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000769 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000770 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000771 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000772
John McCall93ba8572010-03-25 06:39:04 +0000773 if (Qualifier)
774 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000775
John McCalle29ba202009-08-20 01:44:21 +0000776 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000777 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
778 D->getIdentifier(), InstParams, RecordInst,
779 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000780 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000781
John McCall93ba8572010-03-25 06:39:04 +0000782 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000783 if (PrevClassTemplate)
784 Inst->setAccess(PrevClassTemplate->getAccess());
785 else
786 Inst->setAccess(D->getAccess());
787
John McCall93ba8572010-03-25 06:39:04 +0000788 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
789 // TODO: do we want to track the instantiation progeny of this
790 // friend target decl?
791 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000792 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000793 if (!PrevClassTemplate)
794 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000795 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000796
797 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000798 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000799 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000800
Douglas Gregor259571e2009-10-30 22:42:42 +0000801 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000802 if (isFriend) {
803 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000804 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000805 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000806
John McCalle29ba202009-08-20 01:44:21 +0000807 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000808
809 if (!PrevClassTemplate) {
810 // Queue up any out-of-line partial specializations of this member
811 // class template; the client will force their instantiation once
812 // the enclosing class has been instantiated.
813 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
814 D->getPartialSpecializations(PartialSpecs);
815 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
816 if (PartialSpecs[I]->isOutOfLine())
817 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
818 }
819
John McCalle29ba202009-08-20 01:44:21 +0000820 return Inst;
821}
822
Douglas Gregord60e1052009-08-27 16:57:43 +0000823Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000824TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
825 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000826 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
827
828 // Lookup the already-instantiated declaration in the instantiation
829 // of the class template and return that.
830 DeclContext::lookup_result Found
831 = Owner->lookup(ClassTemplate->getDeclName());
832 if (Found.first == Found.second)
833 return 0;
834
835 ClassTemplateDecl *InstClassTemplate
836 = dyn_cast<ClassTemplateDecl>(*Found.first);
837 if (!InstClassTemplate)
838 return 0;
839
Douglas Gregord65587f2010-11-10 19:44:59 +0000840 if (ClassTemplatePartialSpecializationDecl *Result
841 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
842 return Result;
843
844 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000845}
846
847Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000848TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000849 // Create a local instantiation scope for this function template, which
850 // will contain the instantiations of the template parameters and then get
851 // merged with the local instantiation scope for the function template
852 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000853 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000854
Douglas Gregord60e1052009-08-27 16:57:43 +0000855 TemplateParameterList *TempParams = D->getTemplateParameters();
856 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000857 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000858 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000859
Douglas Gregora735b202009-10-13 14:39:41 +0000860 FunctionDecl *Instantiated = 0;
861 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
862 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
863 InstParams));
864 else
865 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
866 D->getTemplatedDecl(),
867 InstParams));
868
869 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000870 return 0;
871
John McCall46460a62010-01-20 21:53:11 +0000872 Instantiated->setAccess(D->getAccess());
873
Mike Stump1eb44332009-09-09 15:08:12 +0000874 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000875 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000876 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000877 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000878 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000879 assert(InstTemplate &&
880 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000881
John McCallb1a56e72010-03-26 23:10:15 +0000882 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
883
John McCalle976ffe2009-12-14 23:19:40 +0000884 // Link the instantiation back to the pattern *unless* this is a
885 // non-definition friend declaration.
886 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000887 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000888 InstTemplate->setInstantiatedFromMemberTemplate(D);
889
John McCallb1a56e72010-03-26 23:10:15 +0000890 // Make declarations visible in the appropriate context.
891 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000892 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000893
Douglas Gregord60e1052009-08-27 16:57:43 +0000894 return InstTemplate;
895}
896
Douglas Gregord475b8d2009-03-25 21:17:03 +0000897Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
898 CXXRecordDecl *PrevDecl = 0;
899 if (D->isInjectedClassName())
900 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000901 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000902 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
903 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000904 TemplateArgs);
905 if (!Prev) return 0;
906 PrevDecl = cast<CXXRecordDecl>(Prev);
907 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000908
909 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000910 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000911 D->getLocation(), D->getIdentifier(),
912 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000913
914 // Substitute the nested name specifier, if any.
915 if (SubstQualifier(D, Record))
916 return 0;
917
Douglas Gregord475b8d2009-03-25 21:17:03 +0000918 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000919 // FIXME: Check against AS_none is an ugly hack to work around the issue that
920 // the tag decls introduced by friend class declarations don't have an access
921 // specifier. Remove once this area of the code gets sorted out.
922 if (D->getAccess() != AS_none)
923 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000924 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000925 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000926
John McCall02cace72009-08-28 07:59:38 +0000927 // If the original function was part of a friend declaration,
928 // inherit its namespace state.
929 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
930 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
931
Douglas Gregor9901c572010-05-21 00:31:19 +0000932 // Make sure that anonymous structs and unions are recorded.
933 if (D->isAnonymousStructOrUnion()) {
934 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000935 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000936 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
937 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000938
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000939 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000940 return Record;
941}
942
John McCall02cace72009-08-28 07:59:38 +0000943/// Normal class members are of more specific types and therefore
944/// don't make it here. This function serves two purposes:
945/// 1) instantiating function templates
946/// 2) substituting friend declarations
947/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000948Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000949 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000950 // Check whether there is already a function template specialization for
951 // this declaration.
952 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
953 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000954 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000955 std::pair<const TemplateArgument *, unsigned> Innermost
956 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000958 FunctionDecl *SpecFunc
959 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
960 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregor127102b2009-06-29 20:59:39 +0000962 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000963 if (SpecFunc)
964 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
John McCallb0cb0222010-03-27 05:57:59 +0000967 bool isFriend;
968 if (FunctionTemplate)
969 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
970 else
971 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
972
Douglas Gregor79c22782010-01-16 20:21:20 +0000973 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000974 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000975 !(isa<Decl>(Owner) &&
976 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000977 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregore53060f2009-06-25 22:08:12 +0000979 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000980 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
981 TInfo = SubstFunctionType(D, Params);
982 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000983 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000984 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000985
John McCalld325daa2010-03-26 04:53:08 +0000986 NestedNameSpecifier *Qualifier = D->getQualifier();
987 if (Qualifier) {
988 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
989 D->getQualifierRange(),
990 TemplateArgs);
991 if (!Qualifier) return 0;
992 }
993
John McCall68b6b872010-02-06 01:50:47 +0000994 // If we're instantiating a local function declaration, put the result
995 // in the owner; otherwise we need to find the instantiated context.
996 DeclContext *DC;
997 if (D->getDeclContext()->isFunctionOrMethod())
998 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000999 else if (isFriend && Qualifier) {
1000 CXXScopeSpec SS;
1001 SS.setScopeRep(Qualifier);
1002 SS.setRange(D->getQualifierRange());
1003 DC = SemaRef.computeDeclContext(SS);
1004 if (!DC) return 0;
1005 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001006 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1007 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001008 }
John McCall68b6b872010-02-06 01:50:47 +00001009
John McCall02cace72009-08-28 07:59:38 +00001010 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001011 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001012 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001013 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001014 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001015
John McCalld325daa2010-03-26 04:53:08 +00001016 if (Qualifier)
1017 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001018
John McCallb1a56e72010-03-26 23:10:15 +00001019 DeclContext *LexicalDC = Owner;
1020 if (!isFriend && D->isOutOfLine()) {
1021 assert(D->getDeclContext()->isFileContext());
1022 LexicalDC = D->getDeclContext();
1023 }
1024
1025 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Douglas Gregore53060f2009-06-25 22:08:12 +00001027 // Attach the parameters
1028 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001029 if (Params[P])
1030 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001031 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001032
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001033 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001034 if (TemplateParams) {
1035 // Our resulting instantiation is actually a function template, since we
1036 // are substituting only the outer template parameters. For example, given
1037 //
1038 // template<typename T>
1039 // struct X {
1040 // template<typename U> friend void f(T, U);
1041 // };
1042 //
1043 // X<int> x;
1044 //
1045 // We are instantiating the friend function template "f" within X<int>,
1046 // which means substituting int for T, but leaving "f" as a friend function
1047 // template.
1048 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001049 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001050 Function->getLocation(),
1051 Function->getDeclName(),
1052 TemplateParams, Function);
1053 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001054
1055 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001056
1057 if (isFriend && D->isThisDeclarationADefinition()) {
1058 // TODO: should we remember this connection regardless of whether
1059 // the friend declaration provided a body?
1060 FunctionTemplate->setInstantiatedFromMemberTemplate(
1061 D->getDescribedFunctionTemplate());
1062 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001063 } else if (FunctionTemplate) {
1064 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001065 std::pair<const TemplateArgument *, unsigned> Innermost
1066 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001067 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001068 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001069 Innermost.first,
1070 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001071 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001072 } else if (isFriend && D->isThisDeclarationADefinition()) {
1073 // TODO: should we remember this connection regardless of whether
1074 // the friend declaration provided a body?
1075 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001076 }
Douglas Gregora735b202009-10-13 14:39:41 +00001077
Douglas Gregore53060f2009-06-25 22:08:12 +00001078 if (InitFunctionInstantiation(Function, D))
1079 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Douglas Gregore53060f2009-06-25 22:08:12 +00001081 bool Redeclaration = false;
1082 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001083 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001084
John McCall68263142009-11-18 22:49:29 +00001085 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1086 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1087
John McCallaf2094e2010-04-08 09:05:18 +00001088 if (DependentFunctionTemplateSpecializationInfo *Info
1089 = D->getDependentSpecializationInfo()) {
1090 assert(isFriend && "non-friend has dependent specialization info?");
1091
1092 // This needs to be set now for future sanity.
1093 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1094
1095 // Instantiate the explicit template arguments.
1096 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1097 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001098 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1099 ExplicitArgs, TemplateArgs))
1100 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001101
1102 // Map the candidate templates to their instantiations.
1103 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1104 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1105 Info->getTemplate(I),
1106 TemplateArgs);
1107 if (!Temp) return 0;
1108
1109 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1110 }
1111
1112 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1113 &ExplicitArgs,
1114 Previous))
1115 Function->setInvalidDecl();
1116
1117 isExplicitSpecialization = true;
1118
1119 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001120 // Look only into the namespace where the friend would be declared to
1121 // find a previous declaration. This is the innermost enclosing namespace,
1122 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001123 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001124
Douglas Gregora735b202009-10-13 14:39:41 +00001125 // In C++, the previous declaration we find might be a tag type
1126 // (class or enum). In this case, the new declaration will hide the
1127 // tag type. Note that this does does not apply if we're declaring a
1128 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001129 if (Previous.isSingleTagDecl())
1130 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001131 }
1132
John McCall9f54ad42009-12-10 09:41:52 +00001133 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001134 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001135 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001136
John McCall76d32642010-04-24 01:30:58 +00001137 NamedDecl *PrincipalDecl = (TemplateParams
1138 ? cast<NamedDecl>(FunctionTemplate)
1139 : Function);
1140
Douglas Gregora735b202009-10-13 14:39:41 +00001141 // If the original function was part of a friend declaration,
1142 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001143 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001144 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001145 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001146 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001147 else
Douglas Gregora735b202009-10-13 14:39:41 +00001148 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001149
1150 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1151 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001152
Gabor Greif77535df2010-08-30 22:25:56 +00001153 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001154
Douglas Gregor238058c2010-05-18 05:45:02 +00001155 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1156 D->isThisDeclarationADefinition()) {
1157 // Check for a function body.
1158 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001159 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001160 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1161 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1162 << Function->getDeclName();
1163 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1164 Function->setInvalidDecl();
1165 }
1166 // Check for redefinitions due to other instantiations of this or
1167 // a similar friend function.
1168 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1169 REnd = Function->redecls_end();
1170 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001171 if (*R == Function)
1172 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001173 switch (R->getFriendObjectKind()) {
1174 case Decl::FOK_None:
1175 if (!queuedInstantiation && R->isUsed(false)) {
1176 if (MemberSpecializationInfo *MSInfo
1177 = Function->getMemberSpecializationInfo()) {
1178 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1179 SourceLocation Loc = R->getLocation(); // FIXME
1180 MSInfo->setPointOfInstantiation(Loc);
1181 SemaRef.PendingLocalImplicitInstantiations.push_back(
1182 std::make_pair(Function, Loc));
1183 queuedInstantiation = true;
1184 }
1185 }
1186 }
1187 break;
1188 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001189 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001190 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001191 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001192 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1193 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001194 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001195 Function->setInvalidDecl();
1196 break;
1197 }
1198 }
1199 }
1200 }
Douglas Gregora735b202009-10-13 14:39:41 +00001201 }
1202
John McCall76d32642010-04-24 01:30:58 +00001203 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1204 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1205 PrincipalDecl->setNonMemberOperator();
1206
Douglas Gregore53060f2009-06-25 22:08:12 +00001207 return Function;
1208}
1209
Douglas Gregord60e1052009-08-27 16:57:43 +00001210Decl *
1211TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1212 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001213 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1214 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001215 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001216 // We are creating a function template specialization from a function
1217 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001218 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001219 std::pair<const TemplateArgument *, unsigned> Innermost
1220 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001222 FunctionDecl *SpecFunc
1223 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1224 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Douglas Gregor6b906862009-08-21 00:16:32 +00001226 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001227 if (SpecFunc)
1228 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001229 }
1230
John McCallb0cb0222010-03-27 05:57:59 +00001231 bool isFriend;
1232 if (FunctionTemplate)
1233 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1234 else
1235 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1236
Douglas Gregor79c22782010-01-16 20:21:20 +00001237 bool MergeWithParentScope = (TemplateParams != 0) ||
1238 !(isa<Decl>(Owner) &&
1239 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001240 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001241
John McCall4eab39f2010-10-19 02:26:41 +00001242 // Instantiate enclosing template arguments for friends.
1243 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1244 unsigned NumTempParamLists = 0;
1245 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1246 TempParamLists.set_size(NumTempParamLists);
1247 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1248 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1249 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1250 if (!InstParams)
1251 return NULL;
1252 TempParamLists[I] = InstParams;
1253 }
1254 }
1255
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001256 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001257 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1258 TInfo = SubstFunctionType(D, Params);
1259 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001260 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001261 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001262
Abramo Bagnara723df242010-12-14 22:11:44 +00001263 // \brief If the type of this function, after ignoring parentheses,
1264 // is not *directly* a function type, then we're instantiating a function
1265 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001266 //
1267 // typedef int functype(int, int);
1268 // functype func;
1269 //
1270 // In this case, we'll just go instantiate the ParmVarDecls that we
1271 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001272 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001273 assert(!Params.size() && "Instantiating type could not yield parameters");
1274 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1275 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1276 TemplateArgs);
1277 if (!P)
1278 return 0;
1279
1280 Params.push_back(P);
1281 }
1282 }
1283
John McCallb0cb0222010-03-27 05:57:59 +00001284 NestedNameSpecifier *Qualifier = D->getQualifier();
1285 if (Qualifier) {
1286 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1287 D->getQualifierRange(),
1288 TemplateArgs);
1289 if (!Qualifier) return 0;
1290 }
1291
1292 DeclContext *DC = Owner;
1293 if (isFriend) {
1294 if (Qualifier) {
1295 CXXScopeSpec SS;
1296 SS.setScopeRep(Qualifier);
1297 SS.setRange(D->getQualifierRange());
1298 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001299
1300 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1301 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001302 } else {
1303 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1304 D->getDeclContext(),
1305 TemplateArgs);
1306 }
1307 if (!DC) return 0;
1308 }
1309
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001310 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001311 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001312 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Abramo Bagnara25777432010-08-11 22:01:17 +00001314 DeclarationNameInfo NameInfo
1315 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001316 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001317 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001318 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001319 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001320 Constructor->isInlineSpecified(),
1321 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001322 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001323 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Craig Silversteinb41d8992010-10-21 00:44:50 +00001324 NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001325 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001326 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001327 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001328 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001329 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001330 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001331 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001332 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001333 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1334 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001335 D->isStatic(),
1336 D->getStorageClassAsWritten(),
1337 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001338 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001339
John McCallb0cb0222010-03-27 05:57:59 +00001340 if (Qualifier)
1341 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001342
Douglas Gregord60e1052009-08-27 16:57:43 +00001343 if (TemplateParams) {
1344 // Our resulting instantiation is actually a function template, since we
1345 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001346 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001347 // template<typename T>
1348 // struct X {
1349 // template<typename U> void f(T, U);
1350 // };
1351 //
1352 // X<int> x;
1353 //
1354 // We are instantiating the member template "f" within X<int>, which means
1355 // substituting int for T, but leaving "f" as a member function template.
1356 // Build the function template itself.
1357 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1358 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001359 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001360 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001361 if (isFriend) {
1362 FunctionTemplate->setLexicalDeclContext(Owner);
1363 FunctionTemplate->setObjectOfFriendDecl(true);
1364 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001365 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001366 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001367 } else if (FunctionTemplate) {
1368 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001369 std::pair<const TemplateArgument *, unsigned> Innermost
1370 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001371 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001372 TemplateArgumentList::CreateCopy(SemaRef.Context,
1373 Innermost.first,
1374 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001375 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001376 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001377 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001378 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001379 }
1380
Mike Stump1eb44332009-09-09 15:08:12 +00001381 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001382 // out-of-line, the instantiation will have the same lexical
1383 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001384 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001385 if (NumTempParamLists)
1386 Method->setTemplateParameterListsInfo(SemaRef.Context,
1387 NumTempParamLists,
1388 TempParamLists.data());
1389
John McCallb0cb0222010-03-27 05:57:59 +00001390 Method->setLexicalDeclContext(Owner);
1391 Method->setObjectOfFriendDecl(true);
1392 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001393 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Douglas Gregor5545e162009-03-24 00:38:23 +00001395 // Attach the parameters
1396 for (unsigned P = 0; P < Params.size(); ++P)
1397 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001398 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001399
1400 if (InitMethodInstantiation(Method, D))
1401 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001402
Abramo Bagnara25777432010-08-11 22:01:17 +00001403 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1404 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001405
John McCallb0cb0222010-03-27 05:57:59 +00001406 if (!FunctionTemplate || TemplateParams || isFriend) {
1407 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Douglas Gregordec06662009-08-21 18:42:58 +00001409 // In C++, the previous declaration we find might be a tag type
1410 // (class or enum). In this case, the new declaration will hide the
1411 // tag type. Note that this does does not apply if we're declaring a
1412 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001413 if (Previous.isSingleTagDecl())
1414 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001415 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001416
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001417 bool Redeclaration = false;
1418 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001419 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001420 /*FIXME:*/OverloadableAttrRequired);
1421
Douglas Gregor4ba31362009-12-01 17:24:26 +00001422 if (D->isPure())
1423 SemaRef.CheckPureMethod(Method, SourceRange());
1424
John McCall46460a62010-01-20 21:53:11 +00001425 Method->setAccess(D->getAccess());
1426
John McCallb0cb0222010-03-27 05:57:59 +00001427 if (FunctionTemplate) {
1428 // If there's a function template, let our caller handle it.
1429 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1430 // Don't hide a (potentially) valid declaration with an invalid one.
1431 } else {
1432 NamedDecl *DeclToAdd = (TemplateParams
1433 ? cast<NamedDecl>(FunctionTemplate)
1434 : Method);
1435 if (isFriend)
1436 Record->makeDeclVisibleInContext(DeclToAdd);
1437 else
1438 Owner->addDecl(DeclToAdd);
1439 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001440
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001441 return Method;
1442}
1443
Douglas Gregor615c5d42009-03-24 16:43:20 +00001444Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001445 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001446}
1447
Douglas Gregor03b2b072009-03-24 00:15:49 +00001448Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001449 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001450}
1451
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001452Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001453 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001454}
1455
Douglas Gregor6477b692009-03-25 15:04:13 +00001456ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001457 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001458}
1459
John McCalle29ba202009-08-20 01:44:21 +00001460Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1461 TemplateTypeParmDecl *D) {
1462 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001463 const Type* T = D->getTypeForDecl();
1464 assert(T->isTemplateTypeParmType());
1465 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001466
John McCalle29ba202009-08-20 01:44:21 +00001467 TemplateTypeParmDecl *Inst =
1468 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001469 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001470 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001471 D->wasDeclaredWithTypename(),
1472 D->isParameterPack());
1473
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001474 if (D->hasDefaultArgument())
1475 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001476
Douglas Gregor550d9b22009-10-31 17:21:17 +00001477 // Introduce this template parameter's instantiation into the instantiation
1478 // scope.
1479 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1480
John McCalle29ba202009-08-20 01:44:21 +00001481 return Inst;
1482}
1483
Douglas Gregor33642df2009-10-23 23:25:44 +00001484Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1485 NonTypeTemplateParmDecl *D) {
1486 // Substitute into the type of the non-type template parameter.
1487 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001488 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001489 if (DI) {
1490 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1491 D->getDeclName());
1492 if (DI) T = DI->getType();
1493 } else {
1494 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1495 D->getDeclName());
1496 DI = 0;
1497 }
1498 if (T.isNull())
1499 return 0;
1500
1501 // Check that this type is acceptable for a non-type template parameter.
1502 bool Invalid = false;
1503 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1504 if (T.isNull()) {
1505 T = SemaRef.Context.IntTy;
1506 Invalid = true;
1507 }
1508
1509 NonTypeTemplateParmDecl *Param
1510 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001511 D->getDepth() - TemplateArgs.getNumLevels(),
1512 D->getPosition(), D->getIdentifier(), T,
1513 DI);
Douglas Gregor33642df2009-10-23 23:25:44 +00001514 if (Invalid)
1515 Param->setInvalidDecl();
1516
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001517 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001518
1519 // Introduce this template parameter's instantiation into the instantiation
1520 // scope.
1521 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001522 return Param;
1523}
1524
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001525Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001526TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1527 TemplateTemplateParmDecl *D) {
1528 // Instantiate the template parameter list of the template template parameter.
1529 TemplateParameterList *TempParams = D->getTemplateParameters();
1530 TemplateParameterList *InstParams;
1531 {
1532 // Perform the actual substitution of template parameters within a new,
1533 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001534 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001535 InstParams = SubstTemplateParams(TempParams);
1536 if (!InstParams)
1537 return NULL;
1538 }
1539
1540 // Build the template template parameter.
1541 TemplateTemplateParmDecl *Param
1542 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001543 D->getDepth() - TemplateArgs.getNumLevels(),
1544 D->getPosition(), D->getIdentifier(),
1545 InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001546 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001547
Douglas Gregor9106ef72009-11-11 16:58:32 +00001548 // Introduce this template parameter's instantiation into the instantiation
1549 // scope.
1550 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1551
1552 return Param;
1553}
1554
Douglas Gregor48c32a72009-11-17 06:07:40 +00001555Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1556 // Using directives are never dependent, so they require no explicit
1557
1558 UsingDirectiveDecl *Inst
1559 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1560 D->getNamespaceKeyLocation(),
1561 D->getQualifierRange(), D->getQualifier(),
1562 D->getIdentLocation(),
1563 D->getNominatedNamespace(),
1564 D->getCommonAncestor());
1565 Owner->addDecl(Inst);
1566 return Inst;
1567}
1568
John McCalled976492009-12-04 22:46:56 +00001569Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001570
1571 // The nested name specifier may be dependent, for example
1572 // template <typename T> struct t {
1573 // struct s1 { T f1(); };
1574 // struct s2 : s1 { using s1::f1; };
1575 // };
1576 // template struct t<int>;
1577 // Here, in using s1::f1, s1 refers to t<T>::s1;
1578 // we need to substitute for t<int>::s1.
1579 NestedNameSpecifier *NNS =
1580 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1581 D->getNestedNameRange(),
1582 TemplateArgs);
1583 if (!NNS)
1584 return 0;
1585
1586 // The name info is non-dependent, so no transformation
1587 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001588 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001589
John McCall9f54ad42009-12-10 09:41:52 +00001590 // We only need to do redeclaration lookups if we're in a class
1591 // scope (in fact, it's not really even possible in non-class
1592 // scopes).
1593 bool CheckRedeclaration = Owner->isRecord();
1594
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001595 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1596 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001597
John McCalled976492009-12-04 22:46:56 +00001598 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001599 D->getNestedNameRange(),
1600 D->getUsingLocation(),
Douglas Gregor1b398202010-09-29 17:58:28 +00001601 NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001602 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001603 D->isTypeName());
1604
1605 CXXScopeSpec SS;
Douglas Gregor1b398202010-09-29 17:58:28 +00001606 SS.setScopeRep(NNS);
John McCalled976492009-12-04 22:46:56 +00001607 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001608
1609 if (CheckRedeclaration) {
1610 Prev.setHideTags(false);
1611 SemaRef.LookupQualifiedName(Prev, Owner);
1612
1613 // Check for invalid redeclarations.
1614 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1615 D->isTypeName(), SS,
1616 D->getLocation(), Prev))
1617 NewUD->setInvalidDecl();
1618
1619 }
1620
1621 if (!NewUD->isInvalidDecl() &&
1622 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001623 D->getLocation()))
1624 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001625
John McCalled976492009-12-04 22:46:56 +00001626 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1627 NewUD->setAccess(D->getAccess());
1628 Owner->addDecl(NewUD);
1629
John McCall9f54ad42009-12-10 09:41:52 +00001630 // Don't process the shadow decls for an invalid decl.
1631 if (NewUD->isInvalidDecl())
1632 return NewUD;
1633
John McCall323c3102009-12-22 22:26:37 +00001634 bool isFunctionScope = Owner->isFunctionOrMethod();
1635
John McCall9f54ad42009-12-10 09:41:52 +00001636 // Process the shadow decls.
1637 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1638 I != E; ++I) {
1639 UsingShadowDecl *Shadow = *I;
1640 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001641 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1642 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001643 TemplateArgs));
1644
1645 if (CheckRedeclaration &&
1646 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1647 continue;
1648
1649 UsingShadowDecl *InstShadow
1650 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1651 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001652
1653 if (isFunctionScope)
1654 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001655 }
John McCalled976492009-12-04 22:46:56 +00001656
1657 return NewUD;
1658}
1659
1660Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001661 // Ignore these; we handle them in bulk when processing the UsingDecl.
1662 return 0;
John McCalled976492009-12-04 22:46:56 +00001663}
1664
John McCall7ba107a2009-11-18 02:36:19 +00001665Decl * TemplateDeclInstantiator
1666 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001667 NestedNameSpecifier *NNS =
1668 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1669 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001670 TemplateArgs);
1671 if (!NNS)
1672 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001674 CXXScopeSpec SS;
1675 SS.setRange(D->getTargetNestedNameRange());
1676 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001678 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1679 // Hence, no tranformation is required for it.
1680 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001681 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001682 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001683 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001684 /*instantiation*/ true,
1685 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001686 if (UD)
John McCalled976492009-12-04 22:46:56 +00001687 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1688
John McCall7ba107a2009-11-18 02:36:19 +00001689 return UD;
1690}
1691
1692Decl * TemplateDeclInstantiator
1693 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1694 NestedNameSpecifier *NNS =
1695 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1696 D->getTargetNestedNameRange(),
1697 TemplateArgs);
1698 if (!NNS)
1699 return 0;
1700
1701 CXXScopeSpec SS;
1702 SS.setRange(D->getTargetNestedNameRange());
1703 SS.setScopeRep(NNS);
1704
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001705 DeclarationNameInfo NameInfo
1706 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1707
John McCall7ba107a2009-11-18 02:36:19 +00001708 NamedDecl *UD =
1709 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001710 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001711 /*instantiation*/ true,
1712 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001713 if (UD)
John McCalled976492009-12-04 22:46:56 +00001714 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1715
Anders Carlsson0d8df782009-08-29 19:37:28 +00001716 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001717}
1718
John McCallce3ff2b2009-08-25 22:02:44 +00001719Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001720 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001721 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001722 if (D->isInvalidDecl())
1723 return 0;
1724
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001725 return Instantiator.Visit(D);
1726}
1727
John McCalle29ba202009-08-20 01:44:21 +00001728/// \brief Instantiates a nested template parameter list in the current
1729/// instantiation context.
1730///
1731/// \param L The parameter list to instantiate
1732///
1733/// \returns NULL if there was an error
1734TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001735TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001736 // Get errors for all the parameters before bailing out.
1737 bool Invalid = false;
1738
1739 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001740 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001741 ParamVector Params;
1742 Params.reserve(N);
1743 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1744 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001745 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001746 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001747 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001748 }
1749
1750 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001751 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001752 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001753
1754 TemplateParameterList *InstL
1755 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1756 L->getLAngleLoc(), &Params.front(), N,
1757 L->getRAngleLoc());
1758 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001759}
John McCalle29ba202009-08-20 01:44:21 +00001760
Douglas Gregored9c0f92009-10-29 00:04:11 +00001761/// \brief Instantiate the declaration of a class template partial
1762/// specialization.
1763///
1764/// \param ClassTemplate the (instantiated) class template that is partially
1765// specialized by the instantiation of \p PartialSpec.
1766///
1767/// \param PartialSpec the (uninstantiated) class template partial
1768/// specialization that we are instantiating.
1769///
Douglas Gregord65587f2010-11-10 19:44:59 +00001770/// \returns The instantiated partial specialization, if successful; otherwise,
1771/// NULL to indicate an error.
1772ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001773TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1774 ClassTemplateDecl *ClassTemplate,
1775 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001776 // Create a local instantiation scope for this class template partial
1777 // specialization, which will contain the instantiations of the template
1778 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001779 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001780
Douglas Gregored9c0f92009-10-29 00:04:11 +00001781 // Substitute into the template parameters of the class template partial
1782 // specialization.
1783 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1784 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1785 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001786 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001787
1788 // Substitute into the template arguments of the class template partial
1789 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001790 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001791 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1792 PartialSpec->getNumTemplateArgsAsWritten(),
1793 InstTemplateArgs, TemplateArgs))
1794 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001795
Douglas Gregored9c0f92009-10-29 00:04:11 +00001796 // Check that the template argument list is well-formed for this
1797 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001798 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001799 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1800 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001801 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001802 false,
1803 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001804 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001805
1806 // Figure out where to insert this class template partial specialization
1807 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001808 void *InsertPos = 0;
1809 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001810 = ClassTemplate->findPartialSpecialization(Converted.data(),
1811 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001812
1813 // Build the canonical type that describes the converted template
1814 // arguments of the class template partial specialization.
1815 QualType CanonType
1816 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001817 Converted.data(),
1818 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001819
1820 // Build the fully-sugared type for this class template
1821 // specialization as the user wrote in the specialization
1822 // itself. This means that we'll pretty-print the type retrieved
1823 // from the specialization's declaration the way that the user
1824 // actually wrote the specialization, rather than formatting the
1825 // name based on the "canonical" representation used to store the
1826 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001827 TypeSourceInfo *WrittenTy
1828 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1829 TemplateName(ClassTemplate),
1830 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001831 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001832 CanonType);
1833
1834 if (PrevDecl) {
1835 // We've already seen a partial specialization with the same template
1836 // parameters and template arguments. This can happen, for example, when
1837 // substituting the outer template arguments ends up causing two
1838 // class template partial specializations of a member class template
1839 // to have identical forms, e.g.,
1840 //
1841 // template<typename T, typename U>
1842 // struct Outer {
1843 // template<typename X, typename Y> struct Inner;
1844 // template<typename Y> struct Inner<T, Y>;
1845 // template<typename Y> struct Inner<U, Y>;
1846 // };
1847 //
1848 // Outer<int, int> outer; // error: the partial specializations of Inner
1849 // // have the same signature.
1850 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001851 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001852 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1853 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001854 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001855 }
1856
1857
1858 // Create the class template partial specialization declaration.
1859 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001860 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1861 PartialSpec->getTagKind(),
1862 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001863 PartialSpec->getLocation(),
1864 InstParams,
1865 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001866 Converted.data(),
1867 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001868 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001869 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001870 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001871 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001872 // Substitute the nested name specifier, if any.
1873 if (SubstQualifier(PartialSpec, InstPartialSpec))
1874 return 0;
1875
Douglas Gregored9c0f92009-10-29 00:04:11 +00001876 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001877 InstPartialSpec->setTypeAsWritten(WrittenTy);
1878
Douglas Gregored9c0f92009-10-29 00:04:11 +00001879 // Add this partial specialization to the set of class template partial
1880 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001881 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001882 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001883}
1884
John McCall21ef0fa2010-03-11 09:03:00 +00001885TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001886TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001887 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001888 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1889 assert(OldTInfo && "substituting function without type source info");
1890 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001891 TypeSourceInfo *NewTInfo
1892 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1893 D->getTypeSpecStartLoc(),
1894 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001895 if (!NewTInfo)
1896 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001897
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001898 if (NewTInfo != OldTInfo) {
1899 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001900 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001901 if (FunctionProtoTypeLoc *OldProtoLoc
1902 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001903 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001904 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1905 assert(NewProtoLoc && "Missing prototype?");
1906 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1907 // FIXME: Variadic templates will break this.
1908 Params.push_back(NewProtoLoc->getArg(i));
1909 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001910 OldProtoLoc->getArg(i),
1911 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001912 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001913 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001914 } else {
1915 // The function type itself was not dependent and therefore no
1916 // substitution occurred. However, we still need to instantiate
1917 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001918 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001919 if (FunctionProtoTypeLoc *OldProtoLoc
1920 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1921 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1922 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1923 if (!Parm)
1924 return 0;
1925 Params.push_back(Parm);
1926 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001927 }
1928 }
John McCall21ef0fa2010-03-11 09:03:00 +00001929 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001930}
1931
Mike Stump1eb44332009-09-09 15:08:12 +00001932/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001933/// declaration (New) from the corresponding fields of its template (Tmpl).
1934///
1935/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001936bool
1937TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001938 FunctionDecl *Tmpl) {
1939 if (Tmpl->isDeleted())
1940 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Douglas Gregorcca9e962009-07-01 22:01:06 +00001942 // If we are performing substituting explicitly-specified template arguments
1943 // or deduced template arguments into a function template and we reach this
1944 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001945 // to keeping the new function template specialization. We therefore
1946 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001947 // into a template instantiation for this specific function template
1948 // specialization, which is not a SFINAE context, so that we diagnose any
1949 // further errors in the declaration itself.
1950 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1951 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1952 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1953 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001954 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001955 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001956 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001957 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001958 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001959 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1960 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001961 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001962 }
1963 }
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001965 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1966 assert(Proto && "Function template without prototype?");
1967
1968 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1969 Proto->getNoReturnAttr()) {
1970 // The function has an exception specification or a "noreturn"
1971 // attribute. Substitute into each of the exception types.
1972 llvm::SmallVector<QualType, 4> Exceptions;
1973 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1974 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00001975 if (const PackExpansionType *PackExpansion
1976 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
1977 // We have a pack expansion. Instantiate it.
1978 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1979 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
1980 Unexpanded);
1981 assert(!Unexpanded.empty() &&
1982 "Pack expansion without parameter packs?");
1983
1984 bool Expand = false;
1985 unsigned NumExpansions = 0;
1986 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
1987 SourceRange(),
1988 Unexpanded.data(),
1989 Unexpanded.size(),
1990 TemplateArgs,
1991 Expand, NumExpansions))
1992 break;
1993
1994 if (!Expand) {
1995 // We can't expand this pack expansion into separate arguments yet;
1996 // just substitute into the argument pack.
1997 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1998 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
1999 TemplateArgs,
2000 New->getLocation(), New->getDeclName());
2001 if (T.isNull())
2002 break;
2003
2004 Exceptions.push_back(T);
2005 continue;
2006 }
2007
2008 // Substitute into the pack expansion pattern for each template
2009 bool Invalid = false;
2010 for (unsigned ArgIdx = 0; ArgIdx != NumExpansions; ++ArgIdx) {
2011 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2012
2013 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2014 TemplateArgs,
2015 New->getLocation(), New->getDeclName());
2016 if (T.isNull()) {
2017 Invalid = true;
2018 break;
2019 }
2020
2021 Exceptions.push_back(T);
2022 }
2023
2024 if (Invalid)
2025 break;
2026
2027 continue;
2028 }
2029
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002030 QualType T
2031 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2032 New->getLocation(), New->getDeclName());
2033 if (T.isNull() ||
2034 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2035 continue;
2036
2037 Exceptions.push_back(T);
2038 }
2039
2040 // Rebuild the function type
2041
John McCalle23cf432010-12-14 08:05:40 +00002042 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2043 EPI.HasExceptionSpec = Proto->hasExceptionSpec();
2044 EPI.HasAnyExceptionSpec = Proto->hasAnyExceptionSpec();
2045 EPI.NumExceptions = Exceptions.size();
2046 EPI.Exceptions = Exceptions.data();
2047 EPI.ExtInfo = Proto->getExtInfo();
2048
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002049 const FunctionProtoType *NewProto
2050 = New->getType()->getAs<FunctionProtoType>();
2051 assert(NewProto && "Template instantiation without function prototype?");
2052 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2053 NewProto->arg_type_begin(),
2054 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002055 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002056 }
2057
John McCall1d8d1cc2010-08-01 02:01:53 +00002058 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002059
Douglas Gregore53060f2009-06-25 22:08:12 +00002060 return false;
2061}
2062
Douglas Gregor5545e162009-03-24 00:38:23 +00002063/// \brief Initializes common fields of an instantiated method
2064/// declaration (New) from the corresponding fields of its template
2065/// (Tmpl).
2066///
2067/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002068bool
2069TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002070 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002071 if (InitFunctionInstantiation(New, Tmpl))
2072 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Douglas Gregor5545e162009-03-24 00:38:23 +00002074 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002075 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002076 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002077
2078 // FIXME: attributes
2079 // FIXME: New needs a pointer to Tmpl
2080 return false;
2081}
Douglas Gregora58861f2009-05-13 20:28:22 +00002082
2083/// \brief Instantiate the definition of the given function from its
2084/// template.
2085///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002086/// \param PointOfInstantiation the point at which the instantiation was
2087/// required. Note that this is not precisely a "point of instantiation"
2088/// for the function, but it's close.
2089///
Douglas Gregora58861f2009-05-13 20:28:22 +00002090/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002091/// function template specialization or member function of a class template
2092/// specialization.
2093///
2094/// \param Recursive if true, recursively instantiates any functions that
2095/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002096///
2097/// \param DefinitionRequired if true, then we are performing an explicit
2098/// instantiation where the body of the function is required. Complain if
2099/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002100void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002101 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002102 bool Recursive,
2103 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002104 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002105 return;
2106
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002107 // Never instantiate an explicit specialization.
2108 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2109 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002110
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002111 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002112 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002113 Stmt *Pattern = 0;
2114 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002115 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002116
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002117 if (!Pattern) {
2118 if (DefinitionRequired) {
2119 if (Function->getPrimaryTemplate())
2120 Diag(PointOfInstantiation,
2121 diag::err_explicit_instantiation_undefined_func_template)
2122 << Function->getPrimaryTemplate();
2123 else
2124 Diag(PointOfInstantiation,
2125 diag::err_explicit_instantiation_undefined_member)
2126 << 1 << Function->getDeclName() << Function->getDeclContext();
2127
2128 if (PatternDecl)
2129 Diag(PatternDecl->getLocation(),
2130 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002131 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002132 } else if (Function->getTemplateSpecializationKind()
2133 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002134 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002135 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002136 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002137
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002138 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002139 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002140
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002141 // C++0x [temp.explicit]p9:
2142 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002143 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002144 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002145 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002146 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002147 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002148 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002150 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2151 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002152 return;
2153
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002154 // If we're performing recursive template instantiation, create our own
2155 // queue of pending implicit instantiations that we will instantiate later,
2156 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002157 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002158 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002159 if (Recursive) {
2160 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002161 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Douglas Gregor9679caf2010-05-12 17:27:19 +00002164 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002165 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002166 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002167
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002168 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002169 // recorded, unless we're actually a member function within a local
2170 // class, in which case we need to merge our results with the parent
2171 // scope (of the enclosing function).
2172 bool MergeWithParentScope = false;
2173 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2174 MergeWithParentScope = Rec->isLocalClass();
2175
2176 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002178 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002179 // instantiation scope, and set the parameter names to those used
2180 // in the template.
2181 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2182 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2183 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2184 FunctionParam->setDeclName(PatternParam->getDeclName());
2185 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2186 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002187
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002188 // Enter the scope of this instantiation. We don't use
2189 // PushDeclContext because we don't have a scope.
2190 DeclContext *PreviousContext = CurContext;
2191 CurContext = Function;
2192
Mike Stump1eb44332009-09-09 15:08:12 +00002193 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002194 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002195
2196 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002197 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002198 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2199 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2200 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002201 }
2202
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002203 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002204 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002205
Douglas Gregor52604ab2009-09-11 21:19:12 +00002206 if (Body.isInvalid())
2207 Function->setInvalidDecl();
2208
John McCall9ae2f072010-08-23 23:25:46 +00002209 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002210 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002211
John McCall0c01d182010-03-24 05:22:00 +00002212 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2213
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002214 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002215
2216 DeclGroupRef DG(Function);
2217 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Douglas Gregor60406be2010-01-16 22:29:39 +00002219 // This class may have local implicit instantiations that need to be
2220 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002221 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002222 Scope.Exit();
2223
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002224 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002225 // Define any pending vtables.
2226 DefineUsedVTables();
2227
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002228 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002229 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002230 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002232 // Restore the set of pending vtables.
2233 VTableUses.swap(SavedVTableUses);
2234
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002235 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002236 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002237 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002238}
2239
2240/// \brief Instantiate the definition of the given variable from its
2241/// template.
2242///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002243/// \param PointOfInstantiation the point at which the instantiation was
2244/// required. Note that this is not precisely a "point of instantiation"
2245/// for the function, but it's close.
2246///
2247/// \param Var the already-instantiated declaration of a static member
2248/// variable of a class template specialization.
2249///
2250/// \param Recursive if true, recursively instantiates any functions that
2251/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002252///
2253/// \param DefinitionRequired if true, then we are performing an explicit
2254/// instantiation where an out-of-line definition of the member variable
2255/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002256void Sema::InstantiateStaticDataMemberDefinition(
2257 SourceLocation PointOfInstantiation,
2258 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002259 bool Recursive,
2260 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002261 if (Var->isInvalidDecl())
2262 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Douglas Gregor7caa6822009-07-24 20:34:43 +00002264 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002265 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002266 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002267 assert(Def->isStaticDataMember() && "Not a static data member?");
2268 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Douglas Gregor0d035142009-10-27 18:42:08 +00002270 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002271 // We did not find an out-of-line definition of this static data member,
2272 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002273 // instantiate this definition (or provide a specialization for it) in
2274 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002275 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002276 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002277 Diag(PointOfInstantiation,
2278 diag::err_explicit_instantiation_undefined_member)
2279 << 2 << Var->getDeclName() << Var->getDeclContext();
2280 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002281 } else if (Var->getTemplateSpecializationKind()
2282 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002283 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002284 std::make_pair(Var, PointOfInstantiation));
2285 }
2286
Douglas Gregor7caa6822009-07-24 20:34:43 +00002287 return;
2288 }
2289
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002290 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002291 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002292 return;
2293
2294 // C++0x [temp.explicit]p9:
2295 // Except for inline functions, other explicit instantiation declarations
2296 // have the effect of suppressing the implicit instantiation of the entity
2297 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002298 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002299 == TSK_ExplicitInstantiationDeclaration)
2300 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Douglas Gregor7caa6822009-07-24 20:34:43 +00002302 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2303 if (Inst)
2304 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Douglas Gregor7caa6822009-07-24 20:34:43 +00002306 // If we're performing recursive template instantiation, create our own
2307 // queue of pending implicit instantiations that we will instantiate later,
2308 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002309 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002310 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002311 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Douglas Gregor7caa6822009-07-24 20:34:43 +00002313 // Enter the scope of this instantiation. We don't use
2314 // PushDeclContext because we don't have a scope.
2315 DeclContext *PreviousContext = CurContext;
2316 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002318 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002319 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002320 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002321 CurContext = PreviousContext;
2322
2323 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002324 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2325 assert(MSInfo && "Missing member specialization information?");
2326 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2327 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002328 DeclGroupRef DG(Var);
2329 Consumer.HandleTopLevelDecl(DG);
2330 }
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Douglas Gregor7caa6822009-07-24 20:34:43 +00002332 if (Recursive) {
2333 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002334 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002335 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Douglas Gregor7caa6822009-07-24 20:34:43 +00002337 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002338 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002339 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002340}
Douglas Gregor815215d2009-05-27 05:35:12 +00002341
Anders Carlsson09025312009-08-29 05:16:22 +00002342void
2343Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2344 const CXXConstructorDecl *Tmpl,
2345 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Anders Carlsson09025312009-08-29 05:16:22 +00002347 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002348 bool AnyErrors = false;
2349
Anders Carlsson09025312009-08-29 05:16:22 +00002350 // Instantiate all the initializers.
2351 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002352 InitsEnd = Tmpl->init_end();
2353 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002354 CXXBaseOrMemberInitializer *Init = *Inits;
2355
Chandler Carruth030ef472010-09-03 21:54:20 +00002356 // Only instantiate written initializers, let Sema re-construct implicit
2357 // ones.
2358 if (!Init->isWritten())
2359 continue;
2360
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002361 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002362 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002364 // Instantiate the initializer.
2365 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002366 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002367 AnyErrors = true;
2368 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002369 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002370
Anders Carlsson09025312009-08-29 05:16:22 +00002371 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002372 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002373 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002374 TemplateArgs,
2375 Init->getSourceLocation(),
2376 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002377 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002378 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002379 New->setInvalidDecl();
2380 continue;
2381 }
2382
John McCalla93c9342009-12-07 02:54:59 +00002383 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002384 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002385 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002386 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002387 Init->getRParenLoc(),
2388 New->getParent());
2389 } else if (Init->isMemberInitializer()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002390 FieldDecl *Member = cast<FieldDecl>(FindInstantiatedDecl(
2391 Init->getMemberLocation(),
2392 Init->getMember(),
2393 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002394
2395 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002396 NewArgs.size(),
2397 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002398 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002399 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002400 } else if (Init->isIndirectMemberInitializer()) {
2401 IndirectFieldDecl *IndirectMember =
2402 cast<IndirectFieldDecl>(FindInstantiatedDecl(
2403 Init->getMemberLocation(),
2404 Init->getIndirectMember(), TemplateArgs));
2405
2406 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2407 NewArgs.size(),
2408 Init->getSourceLocation(),
2409 Init->getLParenLoc(),
2410 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002411 }
2412
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002413 if (NewInit.isInvalid()) {
2414 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002415 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002416 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002417 // FIXME: It would be nice if ASTOwningVector had a release function.
2418 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002419
Anders Carlsson09025312009-08-29 05:16:22 +00002420 NewInits.push_back((MemInitTy *)NewInit.get());
2421 }
2422 }
Mike Stump1eb44332009-09-09 15:08:12 +00002423
Anders Carlsson09025312009-08-29 05:16:22 +00002424 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002425 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002426 /*FIXME: ColonLoc */
2427 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002428 NewInits.data(), NewInits.size(),
2429 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002430}
2431
John McCall52a575a2009-08-29 08:11:13 +00002432// TODO: this could be templated if the various decl types used the
2433// same method name.
2434static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2435 ClassTemplateDecl *Instance) {
2436 Pattern = Pattern->getCanonicalDecl();
2437
2438 do {
2439 Instance = Instance->getCanonicalDecl();
2440 if (Pattern == Instance) return true;
2441 Instance = Instance->getInstantiatedFromMemberTemplate();
2442 } while (Instance);
2443
2444 return false;
2445}
2446
Douglas Gregor0d696532009-09-28 06:34:35 +00002447static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2448 FunctionTemplateDecl *Instance) {
2449 Pattern = Pattern->getCanonicalDecl();
2450
2451 do {
2452 Instance = Instance->getCanonicalDecl();
2453 if (Pattern == Instance) return true;
2454 Instance = Instance->getInstantiatedFromMemberTemplate();
2455 } while (Instance);
2456
2457 return false;
2458}
2459
Douglas Gregored9c0f92009-10-29 00:04:11 +00002460static bool
2461isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2462 ClassTemplatePartialSpecializationDecl *Instance) {
2463 Pattern
2464 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2465 do {
2466 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2467 Instance->getCanonicalDecl());
2468 if (Pattern == Instance)
2469 return true;
2470 Instance = Instance->getInstantiatedFromMember();
2471 } while (Instance);
2472
2473 return false;
2474}
2475
John McCall52a575a2009-08-29 08:11:13 +00002476static bool isInstantiationOf(CXXRecordDecl *Pattern,
2477 CXXRecordDecl *Instance) {
2478 Pattern = Pattern->getCanonicalDecl();
2479
2480 do {
2481 Instance = Instance->getCanonicalDecl();
2482 if (Pattern == Instance) return true;
2483 Instance = Instance->getInstantiatedFromMemberClass();
2484 } while (Instance);
2485
2486 return false;
2487}
2488
2489static bool isInstantiationOf(FunctionDecl *Pattern,
2490 FunctionDecl *Instance) {
2491 Pattern = Pattern->getCanonicalDecl();
2492
2493 do {
2494 Instance = Instance->getCanonicalDecl();
2495 if (Pattern == Instance) return true;
2496 Instance = Instance->getInstantiatedFromMemberFunction();
2497 } while (Instance);
2498
2499 return false;
2500}
2501
2502static bool isInstantiationOf(EnumDecl *Pattern,
2503 EnumDecl *Instance) {
2504 Pattern = Pattern->getCanonicalDecl();
2505
2506 do {
2507 Instance = Instance->getCanonicalDecl();
2508 if (Pattern == Instance) return true;
2509 Instance = Instance->getInstantiatedFromMemberEnum();
2510 } while (Instance);
2511
2512 return false;
2513}
2514
John McCalled976492009-12-04 22:46:56 +00002515static bool isInstantiationOf(UsingShadowDecl *Pattern,
2516 UsingShadowDecl *Instance,
2517 ASTContext &C) {
2518 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2519}
2520
2521static bool isInstantiationOf(UsingDecl *Pattern,
2522 UsingDecl *Instance,
2523 ASTContext &C) {
2524 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2525}
2526
John McCall7ba107a2009-11-18 02:36:19 +00002527static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2528 UsingDecl *Instance,
2529 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002530 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002531}
2532
2533static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002534 UsingDecl *Instance,
2535 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002536 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002537}
2538
John McCall52a575a2009-08-29 08:11:13 +00002539static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2540 VarDecl *Instance) {
2541 assert(Instance->isStaticDataMember());
2542
2543 Pattern = Pattern->getCanonicalDecl();
2544
2545 do {
2546 Instance = Instance->getCanonicalDecl();
2547 if (Pattern == Instance) return true;
2548 Instance = Instance->getInstantiatedFromStaticDataMember();
2549 } while (Instance);
2550
2551 return false;
2552}
2553
John McCalled976492009-12-04 22:46:56 +00002554// Other is the prospective instantiation
2555// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002556static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002557 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002558 if (UnresolvedUsingTypenameDecl *UUD
2559 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2560 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2561 return isInstantiationOf(UUD, UD, Ctx);
2562 }
2563 }
2564
2565 if (UnresolvedUsingValueDecl *UUD
2566 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002567 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2568 return isInstantiationOf(UUD, UD, Ctx);
2569 }
2570 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002571
Anders Carlsson0d8df782009-08-29 19:37:28 +00002572 return false;
2573 }
Mike Stump1eb44332009-09-09 15:08:12 +00002574
John McCall52a575a2009-08-29 08:11:13 +00002575 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2576 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002577
John McCall52a575a2009-08-29 08:11:13 +00002578 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2579 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002580
John McCall52a575a2009-08-29 08:11:13 +00002581 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2582 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002583
Douglas Gregor7caa6822009-07-24 20:34:43 +00002584 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002585 if (Var->isStaticDataMember())
2586 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2587
2588 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2589 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002590
Douglas Gregor0d696532009-09-28 06:34:35 +00002591 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2592 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2593
Douglas Gregored9c0f92009-10-29 00:04:11 +00002594 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2595 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2596 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2597 PartialSpec);
2598
Anders Carlssond8b285f2009-09-01 04:26:58 +00002599 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2600 if (!Field->getDeclName()) {
2601 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002602 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002603 cast<FieldDecl>(D);
2604 }
2605 }
Mike Stump1eb44332009-09-09 15:08:12 +00002606
John McCalled976492009-12-04 22:46:56 +00002607 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2608 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2609
2610 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2611 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2612
Douglas Gregor815215d2009-05-27 05:35:12 +00002613 return D->getDeclName() && isa<NamedDecl>(Other) &&
2614 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2615}
2616
2617template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002618static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002619 NamedDecl *D,
2620 ForwardIterator first,
2621 ForwardIterator last) {
2622 for (; first != last; ++first)
2623 if (isInstantiationOf(Ctx, D, *first))
2624 return cast<NamedDecl>(*first);
2625
2626 return 0;
2627}
2628
John McCall02cace72009-08-28 07:59:38 +00002629/// \brief Finds the instantiation of the given declaration context
2630/// within the current instantiation.
2631///
2632/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002633DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002634 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002635 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002636 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002637 return cast_or_null<DeclContext>(ID);
2638 } else return DC;
2639}
2640
Douglas Gregored961e72009-05-27 17:54:46 +00002641/// \brief Find the instantiation of the given declaration within the
2642/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002643///
2644/// This routine is intended to be used when \p D is a declaration
2645/// referenced from within a template, that needs to mapped into the
2646/// corresponding declaration within an instantiation. For example,
2647/// given:
2648///
2649/// \code
2650/// template<typename T>
2651/// struct X {
2652/// enum Kind {
2653/// KnownValue = sizeof(T)
2654/// };
2655///
2656/// bool getKind() const { return KnownValue; }
2657/// };
2658///
2659/// template struct X<int>;
2660/// \endcode
2661///
2662/// In the instantiation of X<int>::getKind(), we need to map the
2663/// EnumConstantDecl for KnownValue (which refers to
2664/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002665/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2666/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002667NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002668 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002669 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002670 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002671 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002672 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002673 // D is a local of some kind. Look into the map of local
2674 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002675 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002676 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002677
Douglas Gregore95b4092009-09-16 18:34:49 +00002678 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2679 if (!Record->isDependentContext())
2680 return D;
2681
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002682 // If the RecordDecl is actually the injected-class-name or a
2683 // "templated" declaration for a class template, class template
2684 // partial specialization, or a member class of a class template,
2685 // substitute into the injected-class-name of the class template
2686 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002687 QualType T;
2688 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2689
2690 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002691 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002692 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2693 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002694 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002695
2696 // If we call SubstType with an InjectedClassNameType here we
2697 // can end up in an infinite loop.
2698 T = Context.getTypeDeclType(Record);
2699 assert(isa<InjectedClassNameType>(T) &&
2700 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002701 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002702 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002703
2704 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002705 // Substitute into the injected-class-name to get the type
2706 // corresponding to the instantiation we want, which may also be
2707 // the current instantiation (if we're in a template
2708 // definition). This substitution should never fail, since we
2709 // know we can instantiate the injected-class-name or we
2710 // wouldn't have gotten to the injected-class-name!
2711
2712 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2713 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002714 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2715 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2716
2717 if (!T->isDependentType()) {
2718 assert(T->isRecordType() && "Instantiation must produce a record type");
2719 return T->getAs<RecordType>()->getDecl();
2720 }
2721
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002722 // We are performing "partial" template instantiation to create
2723 // the member declarations for the members of a class template
2724 // specialization. Therefore, D is actually referring to something
2725 // in the current instantiation. Look through the current
2726 // context, which contains actual instantiations, to find the
2727 // instantiation of the "current instantiation" that D refers
2728 // to.
2729 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002730 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002731 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002732 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002733 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002734 if (isInstantiationOf(ClassTemplate,
2735 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002736 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002737
2738 if (!DC->isDependentContext())
2739 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002740 }
2741
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002742 // We're performing "instantiation" of a member of the current
2743 // instantiation while we are type-checking the
2744 // definition. Compute the declaration context and return that.
2745 assert(!SawNonDependentContext &&
2746 "No dependent context while instantiating record");
2747 DeclContext *DC = computeDeclContext(T);
2748 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002749 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002750 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002751 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002752
Douglas Gregore95b4092009-09-16 18:34:49 +00002753 // Fall through to deal with other dependent record types (e.g.,
2754 // anonymous unions in class templates).
2755 }
John McCall52a575a2009-08-29 08:11:13 +00002756
Douglas Gregore95b4092009-09-16 18:34:49 +00002757 if (!ParentDC->isDependentContext())
2758 return D;
2759
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002760 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002761 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002762 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Douglas Gregor815215d2009-05-27 05:35:12 +00002764 if (ParentDC != D->getDeclContext()) {
2765 // We performed some kind of instantiation in the parent context,
2766 // so now we need to look into the instantiated parent context to
2767 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002768
John McCall3cb0ebd2010-03-10 03:28:59 +00002769 // If our context used to be dependent, we may need to instantiate
2770 // it before performing lookup into that context.
2771 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002772 if (!Spec->isDependentContext()) {
2773 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002774 const RecordType *Tag = T->getAs<RecordType>();
2775 assert(Tag && "type of non-dependent record is not a RecordType");
2776 if (!Tag->isBeingDefined() &&
2777 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2778 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00002779
2780 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002781 }
2782 }
2783
Douglas Gregor815215d2009-05-27 05:35:12 +00002784 NamedDecl *Result = 0;
2785 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002786 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002787 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2788 } else {
2789 // Since we don't have a name for the entity we're looking for,
2790 // our only option is to walk through all of the declarations to
2791 // find that name. This will occur in a few cases:
2792 //
2793 // - anonymous struct/union within a template
2794 // - unnamed class/struct/union/enum within a template
2795 //
2796 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002797 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002798 ParentDC->decls_begin(),
2799 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002800 }
Mike Stump1eb44332009-09-09 15:08:12 +00002801
John McCall9f54ad42009-12-10 09:41:52 +00002802 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002803 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2804 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002805 && "Unable to find instantiation of declaration!");
2806
Douglas Gregor815215d2009-05-27 05:35:12 +00002807 D = Result;
2808 }
2809
Douglas Gregor815215d2009-05-27 05:35:12 +00002810 return D;
2811}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002812
Mike Stump1eb44332009-09-09 15:08:12 +00002813/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002814/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002815void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002816 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00002817 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002818 PendingImplicitInstantiation Inst;
2819
2820 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002821 Inst = PendingInstantiations.front();
2822 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00002823 } else {
2824 Inst = PendingLocalImplicitInstantiations.front();
2825 PendingLocalImplicitInstantiations.pop_front();
2826 }
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Douglas Gregor7caa6822009-07-24 20:34:43 +00002828 // Instantiate function definitions
2829 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00002830 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
2831 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00002832 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
2833 TSK_ExplicitInstantiationDefinition;
2834 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
2835 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002836 continue;
2837 }
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Douglas Gregor7caa6822009-07-24 20:34:43 +00002839 // Instantiate static data member definitions.
2840 VarDecl *Var = cast<VarDecl>(Inst.first);
2841 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002842
Chandler Carruth291b4412010-02-13 10:17:50 +00002843 // Don't try to instantiate declarations if the most recent redeclaration
2844 // is invalid.
2845 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2846 continue;
2847
2848 // Check if the most recent declaration has changed the specialization kind
2849 // and removed the need for implicit instantiation.
2850 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2851 case TSK_Undeclared:
2852 assert(false && "Cannot instantitiate an undeclared specialization.");
2853 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00002854 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00002855 continue; // No longer need to instantiate this type.
2856 case TSK_ExplicitInstantiationDefinition:
2857 // We only need an instantiation if the pending instantiation *is* the
2858 // explicit instantiation.
2859 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00002860 case TSK_ImplicitInstantiation:
2861 break;
2862 }
2863
John McCallf312b1e2010-08-26 23:41:50 +00002864 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
2865 "instantiating static data member "
2866 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Chandler Carruth58e390e2010-08-25 08:27:02 +00002868 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
2869 TSK_ExplicitInstantiationDefinition;
2870 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
2871 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002872 }
2873}
John McCall0c01d182010-03-24 05:22:00 +00002874
2875void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2876 const MultiLevelTemplateArgumentList &TemplateArgs) {
2877 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2878 E = Pattern->ddiag_end(); I != E; ++I) {
2879 DependentDiagnostic *DD = *I;
2880
2881 switch (DD->getKind()) {
2882 case DependentDiagnostic::Access:
2883 HandleDependentAccessCheck(*DD, TemplateArgs);
2884 break;
2885 }
2886 }
2887}