blob: b45fb821d92596d1d1ae4171245a1c7d991fb8b1 [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
217 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
218 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
470 IndirectFieldDecl* IndirectField
471 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
472 D->getIdentifier(), D->getType(),
473 NamedChain, D->getChainingSize());
474
475
476 IndirectField->setImplicit(D->isImplicit());
477 IndirectField->setAccess(D->getAccess());
478 Owner->addDecl(IndirectField);
479 return IndirectField;
480}
481
John McCall02cace72009-08-28 07:59:38 +0000482Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000483 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000484 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000485 if (TypeSourceInfo *Ty = D->getFriendType()) {
486 TypeSourceInfo *InstTy =
487 SemaRef.SubstType(Ty, TemplateArgs,
488 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000489 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000490 return 0;
John McCall02cace72009-08-28 07:59:38 +0000491
Douglas Gregor06245bf2010-04-07 17:57:12 +0000492 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
493 if (!FD)
494 return 0;
495
496 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000497 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000498 Owner->addDecl(FD);
499 return FD;
500 }
501
502 NamedDecl *ND = D->getFriendDecl();
503 assert(ND && "friend decl must be a decl or a type!");
504
John McCallaf2094e2010-04-08 09:05:18 +0000505 // All of the Visit implementations for the various potential friend
506 // declarations have to be carefully written to work for friend
507 // objects, with the most important detail being that the target
508 // decl should almost certainly not be placed in Owner.
509 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000510 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
John McCall02cace72009-08-28 07:59:38 +0000512 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000513 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
514 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000515 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000516 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000517 Owner->addDecl(FD);
518 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000519}
520
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000521Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
522 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Douglas Gregorac7610d2009-06-22 20:57:11 +0000524 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000525 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000526
John McCall60d7b3a2010-08-24 06:29:42 +0000527 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000528 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000529 if (InstantiatedAssertExpr.isInvalid())
530 return 0;
531
John McCall60d7b3a2010-08-24 06:29:42 +0000532 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000533 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000534 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000535 InstantiatedAssertExpr.get(),
536 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000537}
538
539Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000540 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000541 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000542 D->getTagKeywordLoc(),
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000543 /*PrevDecl=*/0,
544 D->isScoped(), D->isFixed());
545 if (D->isFixed()) {
546 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
547 // If we have type source information for the underlying type, it means it
548 // has been explicitly set by the user. Perform substitution on it before
549 // moving on.
550 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
551 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
552 TemplateArgs,
553 UnderlyingLoc,
554 DeclarationName()));
555
556 if (!Enum->getIntegerTypeSourceInfo())
557 Enum->setIntegerType(SemaRef.Context.IntTy);
558 }
559 else {
560 assert(!D->getIntegerType()->isDependentType()
561 && "Dependent type without type source info");
562 Enum->setIntegerType(D->getIntegerType());
563 }
564 }
565
John McCall5b629aa2010-10-22 23:36:17 +0000566 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
567
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000568 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000569 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000570 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000571 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000572 Enum->startDefinition();
573
Douglas Gregor96084f12010-03-01 19:00:07 +0000574 if (D->getDeclContext()->isFunctionOrMethod())
575 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
576
John McCalld226f652010-08-21 09:40:31 +0000577 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000578
579 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000580 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
581 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000582 EC != ECEnd; ++EC) {
583 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000584 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000585 if (Expr *UninstValue = EC->getInitExpr()) {
586 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000587 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000588 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000589
John McCallce3ff2b2009-08-25 22:02:44 +0000590 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000591 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000592
593 // Drop the initial value and continue.
594 bool isInvalid = false;
595 if (Value.isInvalid()) {
596 Value = SemaRef.Owned((Expr *)0);
597 isInvalid = true;
598 }
599
Mike Stump1eb44332009-09-09 15:08:12 +0000600 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000601 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
602 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000603 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000604
605 if (isInvalid) {
606 if (EnumConst)
607 EnumConst->setInvalidDecl();
608 Enum->setInvalidDecl();
609 }
610
611 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000612 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
613
John McCall3b85ecf2010-01-23 22:37:59 +0000614 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000615 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000616 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000617 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000618
619 if (D->getDeclContext()->isFunctionOrMethod()) {
620 // If the enumeration is within a function or method, record the enum
621 // constant as a local.
622 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
623 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000624 }
625 }
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000627 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000628 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000629 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000630 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000631 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000632 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000633
634 return Enum;
635}
636
Douglas Gregor6477b692009-03-25 15:04:13 +0000637Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
638 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
639 return 0;
640}
641
John McCalle29ba202009-08-20 01:44:21 +0000642Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000643 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
644
Douglas Gregor550d9b22009-10-31 17:21:17 +0000645 // Create a local instantiation scope for this class template, which
646 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000647 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000648 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000649 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000650 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000651 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000652
653 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000654
655 // Instantiate the qualifier. We have to do this first in case
656 // we're a friend declaration, because if we are then we need to put
657 // the new declaration in the appropriate context.
658 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
659 if (Qualifier) {
660 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
661 Pattern->getQualifierRange(),
662 TemplateArgs);
663 if (!Qualifier) return 0;
664 }
665
666 CXXRecordDecl *PrevDecl = 0;
667 ClassTemplateDecl *PrevClassTemplate = 0;
668
Nick Lewycky37574f52010-11-08 23:29:42 +0000669 if (!isFriend && Pattern->getPreviousDeclaration()) {
670 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
671 if (Found.first != Found.second) {
672 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
673 if (PrevClassTemplate)
674 PrevDecl = PrevClassTemplate->getTemplatedDecl();
675 }
676 }
677
John McCall93ba8572010-03-25 06:39:04 +0000678 // If this isn't a friend, then it's a member template, in which
679 // case we just want to build the instantiation in the
680 // specialization. If it is a friend, we want to build it in
681 // the appropriate context.
682 DeclContext *DC = Owner;
683 if (isFriend) {
684 if (Qualifier) {
685 CXXScopeSpec SS;
686 SS.setScopeRep(Qualifier);
687 SS.setRange(Pattern->getQualifierRange());
688 DC = SemaRef.computeDeclContext(SS);
689 if (!DC) return 0;
690 } else {
691 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
692 Pattern->getDeclContext(),
693 TemplateArgs);
694 }
695
696 // Look for a previous declaration of the template in the owning
697 // context.
698 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
699 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
700 SemaRef.LookupQualifiedName(R, DC);
701
702 if (R.isSingleResult()) {
703 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
704 if (PrevClassTemplate)
705 PrevDecl = PrevClassTemplate->getTemplatedDecl();
706 }
707
708 if (!PrevClassTemplate && Qualifier) {
709 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000710 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
711 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000712 return 0;
713 }
714
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000715 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000716 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000717 bool Complain = true;
718
719 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
720 // template for struct std::tr1::__detail::_Map_base, where the
721 // template parameters of the friend declaration don't match the
722 // template parameters of the original declaration. In this one
723 // case, we don't complain about the ill-formed friend
724 // declaration.
725 if (isFriend && Pattern->getIdentifier() &&
726 Pattern->getIdentifier()->isStr("_Map_base") &&
727 DC->isNamespace() &&
728 cast<NamespaceDecl>(DC)->getIdentifier() &&
729 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
730 DeclContext *DCParent = DC->getParent();
731 if (DCParent->isNamespace() &&
732 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
733 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
734 DeclContext *DCParent2 = DCParent->getParent();
735 if (DCParent2->isNamespace() &&
736 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
737 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
738 DCParent2->getParent()->isTranslationUnit())
739 Complain = false;
740 }
741 }
742
John McCall93ba8572010-03-25 06:39:04 +0000743 TemplateParameterList *PrevParams
744 = PrevClassTemplate->getTemplateParameters();
745
746 // Make sure the parameter lists match.
747 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000748 Complain,
749 Sema::TPL_TemplateMatch)) {
750 if (Complain)
751 return 0;
752
753 AdoptedPreviousTemplateParams = true;
754 InstParams = PrevParams;
755 }
John McCall93ba8572010-03-25 06:39:04 +0000756
757 // Do some additional validation, then merge default arguments
758 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000759 if (!AdoptedPreviousTemplateParams &&
760 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000761 Sema::TPC_ClassTemplate))
762 return 0;
763 }
764 }
765
John McCalle29ba202009-08-20 01:44:21 +0000766 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000767 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000768 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000769 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000770 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000771
John McCall93ba8572010-03-25 06:39:04 +0000772 if (Qualifier)
773 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000774
John McCalle29ba202009-08-20 01:44:21 +0000775 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000776 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
777 D->getIdentifier(), InstParams, RecordInst,
778 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000779 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000780
John McCall93ba8572010-03-25 06:39:04 +0000781 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000782 if (PrevClassTemplate)
783 Inst->setAccess(PrevClassTemplate->getAccess());
784 else
785 Inst->setAccess(D->getAccess());
786
John McCall93ba8572010-03-25 06:39:04 +0000787 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
788 // TODO: do we want to track the instantiation progeny of this
789 // friend target decl?
790 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000791 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000792 if (!PrevClassTemplate)
793 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000794 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000795
796 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000797 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000798 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000799
Douglas Gregor259571e2009-10-30 22:42:42 +0000800 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000801 if (isFriend) {
802 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000803 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000804 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000805
John McCalle29ba202009-08-20 01:44:21 +0000806 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000807
808 if (!PrevClassTemplate) {
809 // Queue up any out-of-line partial specializations of this member
810 // class template; the client will force their instantiation once
811 // the enclosing class has been instantiated.
812 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
813 D->getPartialSpecializations(PartialSpecs);
814 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
815 if (PartialSpecs[I]->isOutOfLine())
816 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
817 }
818
John McCalle29ba202009-08-20 01:44:21 +0000819 return Inst;
820}
821
Douglas Gregord60e1052009-08-27 16:57:43 +0000822Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000823TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
824 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000825 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
826
827 // Lookup the already-instantiated declaration in the instantiation
828 // of the class template and return that.
829 DeclContext::lookup_result Found
830 = Owner->lookup(ClassTemplate->getDeclName());
831 if (Found.first == Found.second)
832 return 0;
833
834 ClassTemplateDecl *InstClassTemplate
835 = dyn_cast<ClassTemplateDecl>(*Found.first);
836 if (!InstClassTemplate)
837 return 0;
838
Douglas Gregord65587f2010-11-10 19:44:59 +0000839 if (ClassTemplatePartialSpecializationDecl *Result
840 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
841 return Result;
842
843 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000844}
845
846Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000847TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000848 // Create a local instantiation scope for this function template, which
849 // will contain the instantiations of the template parameters and then get
850 // merged with the local instantiation scope for the function template
851 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000852 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000853
Douglas Gregord60e1052009-08-27 16:57:43 +0000854 TemplateParameterList *TempParams = D->getTemplateParameters();
855 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000856 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000857 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000858
Douglas Gregora735b202009-10-13 14:39:41 +0000859 FunctionDecl *Instantiated = 0;
860 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
861 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
862 InstParams));
863 else
864 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
865 D->getTemplatedDecl(),
866 InstParams));
867
868 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000869 return 0;
870
John McCall46460a62010-01-20 21:53:11 +0000871 Instantiated->setAccess(D->getAccess());
872
Mike Stump1eb44332009-09-09 15:08:12 +0000873 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000874 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000875 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000876 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000877 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000878 assert(InstTemplate &&
879 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000880
John McCallb1a56e72010-03-26 23:10:15 +0000881 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
882
John McCalle976ffe2009-12-14 23:19:40 +0000883 // Link the instantiation back to the pattern *unless* this is a
884 // non-definition friend declaration.
885 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000886 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000887 InstTemplate->setInstantiatedFromMemberTemplate(D);
888
John McCallb1a56e72010-03-26 23:10:15 +0000889 // Make declarations visible in the appropriate context.
890 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000891 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000892
Douglas Gregord60e1052009-08-27 16:57:43 +0000893 return InstTemplate;
894}
895
Douglas Gregord475b8d2009-03-25 21:17:03 +0000896Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
897 CXXRecordDecl *PrevDecl = 0;
898 if (D->isInjectedClassName())
899 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000900 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000901 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
902 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000903 TemplateArgs);
904 if (!Prev) return 0;
905 PrevDecl = cast<CXXRecordDecl>(Prev);
906 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000907
908 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000909 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000910 D->getLocation(), D->getIdentifier(),
911 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000912
913 // Substitute the nested name specifier, if any.
914 if (SubstQualifier(D, Record))
915 return 0;
916
Douglas Gregord475b8d2009-03-25 21:17:03 +0000917 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000918 // FIXME: Check against AS_none is an ugly hack to work around the issue that
919 // the tag decls introduced by friend class declarations don't have an access
920 // specifier. Remove once this area of the code gets sorted out.
921 if (D->getAccess() != AS_none)
922 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000923 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000924 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000925
John McCall02cace72009-08-28 07:59:38 +0000926 // If the original function was part of a friend declaration,
927 // inherit its namespace state.
928 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
929 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
930
Douglas Gregor9901c572010-05-21 00:31:19 +0000931 // Make sure that anonymous structs and unions are recorded.
932 if (D->isAnonymousStructOrUnion()) {
933 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000934 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000935 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
936 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000937
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000938 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000939 return Record;
940}
941
John McCall02cace72009-08-28 07:59:38 +0000942/// Normal class members are of more specific types and therefore
943/// don't make it here. This function serves two purposes:
944/// 1) instantiating function templates
945/// 2) substituting friend declarations
946/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000947Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000948 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000949 // Check whether there is already a function template specialization for
950 // this declaration.
951 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
952 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000953 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000954 std::pair<const TemplateArgument *, unsigned> Innermost
955 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000957 FunctionDecl *SpecFunc
958 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
959 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Douglas Gregor127102b2009-06-29 20:59:39 +0000961 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000962 if (SpecFunc)
963 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
John McCallb0cb0222010-03-27 05:57:59 +0000966 bool isFriend;
967 if (FunctionTemplate)
968 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
969 else
970 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
971
Douglas Gregor79c22782010-01-16 20:21:20 +0000972 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000973 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000974 !(isa<Decl>(Owner) &&
975 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000976 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Douglas Gregore53060f2009-06-25 22:08:12 +0000978 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000979 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
980 TInfo = SubstFunctionType(D, Params);
981 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000982 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000983 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000984
John McCalld325daa2010-03-26 04:53:08 +0000985 NestedNameSpecifier *Qualifier = D->getQualifier();
986 if (Qualifier) {
987 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
988 D->getQualifierRange(),
989 TemplateArgs);
990 if (!Qualifier) return 0;
991 }
992
John McCall68b6b872010-02-06 01:50:47 +0000993 // If we're instantiating a local function declaration, put the result
994 // in the owner; otherwise we need to find the instantiated context.
995 DeclContext *DC;
996 if (D->getDeclContext()->isFunctionOrMethod())
997 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000998 else if (isFriend && Qualifier) {
999 CXXScopeSpec SS;
1000 SS.setScopeRep(Qualifier);
1001 SS.setRange(D->getQualifierRange());
1002 DC = SemaRef.computeDeclContext(SS);
1003 if (!DC) return 0;
1004 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001005 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1006 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001007 }
John McCall68b6b872010-02-06 01:50:47 +00001008
John McCall02cace72009-08-28 07:59:38 +00001009 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001010 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001011 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001012 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001013 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001014
John McCalld325daa2010-03-26 04:53:08 +00001015 if (Qualifier)
1016 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001017
John McCallb1a56e72010-03-26 23:10:15 +00001018 DeclContext *LexicalDC = Owner;
1019 if (!isFriend && D->isOutOfLine()) {
1020 assert(D->getDeclContext()->isFileContext());
1021 LexicalDC = D->getDeclContext();
1022 }
1023
1024 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Douglas Gregore53060f2009-06-25 22:08:12 +00001026 // Attach the parameters
1027 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001028 if (Params[P])
1029 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001030 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001031
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001032 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001033 if (TemplateParams) {
1034 // Our resulting instantiation is actually a function template, since we
1035 // are substituting only the outer template parameters. For example, given
1036 //
1037 // template<typename T>
1038 // struct X {
1039 // template<typename U> friend void f(T, U);
1040 // };
1041 //
1042 // X<int> x;
1043 //
1044 // We are instantiating the friend function template "f" within X<int>,
1045 // which means substituting int for T, but leaving "f" as a friend function
1046 // template.
1047 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001048 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001049 Function->getLocation(),
1050 Function->getDeclName(),
1051 TemplateParams, Function);
1052 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001053
1054 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001055
1056 if (isFriend && D->isThisDeclarationADefinition()) {
1057 // TODO: should we remember this connection regardless of whether
1058 // the friend declaration provided a body?
1059 FunctionTemplate->setInstantiatedFromMemberTemplate(
1060 D->getDescribedFunctionTemplate());
1061 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001062 } else if (FunctionTemplate) {
1063 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001064 std::pair<const TemplateArgument *, unsigned> Innermost
1065 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001066 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001067 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001068 Innermost.first,
1069 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001070 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001071 } else if (isFriend && D->isThisDeclarationADefinition()) {
1072 // TODO: should we remember this connection regardless of whether
1073 // the friend declaration provided a body?
1074 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001075 }
Douglas Gregora735b202009-10-13 14:39:41 +00001076
Douglas Gregore53060f2009-06-25 22:08:12 +00001077 if (InitFunctionInstantiation(Function, D))
1078 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Douglas Gregore53060f2009-06-25 22:08:12 +00001080 bool Redeclaration = false;
1081 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001082 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001083
John McCall68263142009-11-18 22:49:29 +00001084 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1085 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1086
John McCallaf2094e2010-04-08 09:05:18 +00001087 if (DependentFunctionTemplateSpecializationInfo *Info
1088 = D->getDependentSpecializationInfo()) {
1089 assert(isFriend && "non-friend has dependent specialization info?");
1090
1091 // This needs to be set now for future sanity.
1092 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1093
1094 // Instantiate the explicit template arguments.
1095 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1096 Info->getRAngleLoc());
1097 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1098 TemplateArgumentLoc Loc;
1099 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1100 return 0;
1101
1102 ExplicitArgs.addArgument(Loc);
1103 }
1104
1105 // Map the candidate templates to their instantiations.
1106 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1107 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1108 Info->getTemplate(I),
1109 TemplateArgs);
1110 if (!Temp) return 0;
1111
1112 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1113 }
1114
1115 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1116 &ExplicitArgs,
1117 Previous))
1118 Function->setInvalidDecl();
1119
1120 isExplicitSpecialization = true;
1121
1122 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001123 // Look only into the namespace where the friend would be declared to
1124 // find a previous declaration. This is the innermost enclosing namespace,
1125 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001126 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001127
Douglas Gregora735b202009-10-13 14:39:41 +00001128 // In C++, the previous declaration we find might be a tag type
1129 // (class or enum). In this case, the new declaration will hide the
1130 // tag type. Note that this does does not apply if we're declaring a
1131 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001132 if (Previous.isSingleTagDecl())
1133 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001134 }
1135
John McCall9f54ad42009-12-10 09:41:52 +00001136 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001137 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001138 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001139
John McCall76d32642010-04-24 01:30:58 +00001140 NamedDecl *PrincipalDecl = (TemplateParams
1141 ? cast<NamedDecl>(FunctionTemplate)
1142 : Function);
1143
Douglas Gregora735b202009-10-13 14:39:41 +00001144 // If the original function was part of a friend declaration,
1145 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001146 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001147 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001148 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001149 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001150 else
Douglas Gregora735b202009-10-13 14:39:41 +00001151 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001152
1153 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1154 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001155
Gabor Greif77535df2010-08-30 22:25:56 +00001156 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001157
Douglas Gregor238058c2010-05-18 05:45:02 +00001158 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1159 D->isThisDeclarationADefinition()) {
1160 // Check for a function body.
1161 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001162 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001163 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1164 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1165 << Function->getDeclName();
1166 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1167 Function->setInvalidDecl();
1168 }
1169 // Check for redefinitions due to other instantiations of this or
1170 // a similar friend function.
1171 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1172 REnd = Function->redecls_end();
1173 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001174 if (*R == Function)
1175 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001176 switch (R->getFriendObjectKind()) {
1177 case Decl::FOK_None:
1178 if (!queuedInstantiation && R->isUsed(false)) {
1179 if (MemberSpecializationInfo *MSInfo
1180 = Function->getMemberSpecializationInfo()) {
1181 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1182 SourceLocation Loc = R->getLocation(); // FIXME
1183 MSInfo->setPointOfInstantiation(Loc);
1184 SemaRef.PendingLocalImplicitInstantiations.push_back(
1185 std::make_pair(Function, Loc));
1186 queuedInstantiation = true;
1187 }
1188 }
1189 }
1190 break;
1191 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001192 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001193 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001194 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001195 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1196 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001197 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001198 Function->setInvalidDecl();
1199 break;
1200 }
1201 }
1202 }
1203 }
Douglas Gregora735b202009-10-13 14:39:41 +00001204 }
1205
John McCall76d32642010-04-24 01:30:58 +00001206 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1207 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1208 PrincipalDecl->setNonMemberOperator();
1209
Douglas Gregore53060f2009-06-25 22:08:12 +00001210 return Function;
1211}
1212
Douglas Gregord60e1052009-08-27 16:57:43 +00001213Decl *
1214TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1215 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001216 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1217 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001218 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001219 // We are creating a function template specialization from a function
1220 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001221 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001222 std::pair<const TemplateArgument *, unsigned> Innermost
1223 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001225 FunctionDecl *SpecFunc
1226 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1227 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregor6b906862009-08-21 00:16:32 +00001229 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001230 if (SpecFunc)
1231 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001232 }
1233
John McCallb0cb0222010-03-27 05:57:59 +00001234 bool isFriend;
1235 if (FunctionTemplate)
1236 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1237 else
1238 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1239
Douglas Gregor79c22782010-01-16 20:21:20 +00001240 bool MergeWithParentScope = (TemplateParams != 0) ||
1241 !(isa<Decl>(Owner) &&
1242 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001243 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001244
John McCall4eab39f2010-10-19 02:26:41 +00001245 // Instantiate enclosing template arguments for friends.
1246 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1247 unsigned NumTempParamLists = 0;
1248 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1249 TempParamLists.set_size(NumTempParamLists);
1250 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1251 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1252 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1253 if (!InstParams)
1254 return NULL;
1255 TempParamLists[I] = InstParams;
1256 }
1257 }
1258
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001259 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001260 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1261 TInfo = SubstFunctionType(D, Params);
1262 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001263 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001264 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001265
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001266 // \brief If the type of this function is not *directly* a function
1267 // type, then we're instantiating the a function that was declared
1268 // via a typedef, e.g.,
1269 //
1270 // typedef int functype(int, int);
1271 // functype func;
1272 //
1273 // In this case, we'll just go instantiate the ParmVarDecls that we
1274 // synthesized in the method declaration.
1275 if (!isa<FunctionProtoType>(T)) {
1276 assert(!Params.size() && "Instantiating type could not yield parameters");
1277 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1278 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1279 TemplateArgs);
1280 if (!P)
1281 return 0;
1282
1283 Params.push_back(P);
1284 }
1285 }
1286
John McCallb0cb0222010-03-27 05:57:59 +00001287 NestedNameSpecifier *Qualifier = D->getQualifier();
1288 if (Qualifier) {
1289 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1290 D->getQualifierRange(),
1291 TemplateArgs);
1292 if (!Qualifier) return 0;
1293 }
1294
1295 DeclContext *DC = Owner;
1296 if (isFriend) {
1297 if (Qualifier) {
1298 CXXScopeSpec SS;
1299 SS.setScopeRep(Qualifier);
1300 SS.setRange(D->getQualifierRange());
1301 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001302
1303 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1304 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001305 } else {
1306 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1307 D->getDeclContext(),
1308 TemplateArgs);
1309 }
1310 if (!DC) return 0;
1311 }
1312
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001313 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001314 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001315 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Abramo Bagnara25777432010-08-11 22:01:17 +00001317 DeclarationNameInfo NameInfo
1318 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001319 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001320 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001321 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001322 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001323 Constructor->isInlineSpecified(),
1324 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001325 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001326 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Craig Silversteinb41d8992010-10-21 00:44:50 +00001327 NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001328 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001329 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001330 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001331 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001332 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001333 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001334 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001335 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001336 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1337 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001338 D->isStatic(),
1339 D->getStorageClassAsWritten(),
1340 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001341 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001342
John McCallb0cb0222010-03-27 05:57:59 +00001343 if (Qualifier)
1344 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001345
Douglas Gregord60e1052009-08-27 16:57:43 +00001346 if (TemplateParams) {
1347 // Our resulting instantiation is actually a function template, since we
1348 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001349 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001350 // template<typename T>
1351 // struct X {
1352 // template<typename U> void f(T, U);
1353 // };
1354 //
1355 // X<int> x;
1356 //
1357 // We are instantiating the member template "f" within X<int>, which means
1358 // substituting int for T, but leaving "f" as a member function template.
1359 // Build the function template itself.
1360 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1361 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001362 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001363 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001364 if (isFriend) {
1365 FunctionTemplate->setLexicalDeclContext(Owner);
1366 FunctionTemplate->setObjectOfFriendDecl(true);
1367 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001368 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001369 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001370 } else if (FunctionTemplate) {
1371 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001372 std::pair<const TemplateArgument *, unsigned> Innermost
1373 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001374 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001375 TemplateArgumentList::CreateCopy(SemaRef.Context,
1376 Innermost.first,
1377 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001378 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001379 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001380 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001381 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001382 }
1383
Mike Stump1eb44332009-09-09 15:08:12 +00001384 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001385 // out-of-line, the instantiation will have the same lexical
1386 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001387 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001388 if (NumTempParamLists)
1389 Method->setTemplateParameterListsInfo(SemaRef.Context,
1390 NumTempParamLists,
1391 TempParamLists.data());
1392
John McCallb0cb0222010-03-27 05:57:59 +00001393 Method->setLexicalDeclContext(Owner);
1394 Method->setObjectOfFriendDecl(true);
1395 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001396 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Douglas Gregor5545e162009-03-24 00:38:23 +00001398 // Attach the parameters
1399 for (unsigned P = 0; P < Params.size(); ++P)
1400 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001401 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001402
1403 if (InitMethodInstantiation(Method, D))
1404 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001405
Abramo Bagnara25777432010-08-11 22:01:17 +00001406 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1407 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
John McCallb0cb0222010-03-27 05:57:59 +00001409 if (!FunctionTemplate || TemplateParams || isFriend) {
1410 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregordec06662009-08-21 18:42:58 +00001412 // In C++, the previous declaration we find might be a tag type
1413 // (class or enum). In this case, the new declaration will hide the
1414 // tag type. Note that this does does not apply if we're declaring a
1415 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001416 if (Previous.isSingleTagDecl())
1417 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001418 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001419
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001420 bool Redeclaration = false;
1421 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001422 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001423 /*FIXME:*/OverloadableAttrRequired);
1424
Douglas Gregor4ba31362009-12-01 17:24:26 +00001425 if (D->isPure())
1426 SemaRef.CheckPureMethod(Method, SourceRange());
1427
John McCall46460a62010-01-20 21:53:11 +00001428 Method->setAccess(D->getAccess());
1429
John McCallb0cb0222010-03-27 05:57:59 +00001430 if (FunctionTemplate) {
1431 // If there's a function template, let our caller handle it.
1432 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1433 // Don't hide a (potentially) valid declaration with an invalid one.
1434 } else {
1435 NamedDecl *DeclToAdd = (TemplateParams
1436 ? cast<NamedDecl>(FunctionTemplate)
1437 : Method);
1438 if (isFriend)
1439 Record->makeDeclVisibleInContext(DeclToAdd);
1440 else
1441 Owner->addDecl(DeclToAdd);
1442 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001443
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001444 return Method;
1445}
1446
Douglas Gregor615c5d42009-03-24 16:43:20 +00001447Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001448 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001449}
1450
Douglas Gregor03b2b072009-03-24 00:15:49 +00001451Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001452 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001453}
1454
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001455Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001456 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001457}
1458
Douglas Gregor6477b692009-03-25 15:04:13 +00001459ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001460 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001461}
1462
John McCalle29ba202009-08-20 01:44:21 +00001463Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1464 TemplateTypeParmDecl *D) {
1465 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001466 const Type* T = D->getTypeForDecl();
1467 assert(T->isTemplateTypeParmType());
1468 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001469
John McCalle29ba202009-08-20 01:44:21 +00001470 TemplateTypeParmDecl *Inst =
1471 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001472 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001473 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001474 D->wasDeclaredWithTypename(),
1475 D->isParameterPack());
1476
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001477 if (D->hasDefaultArgument())
1478 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001479
Douglas Gregor550d9b22009-10-31 17:21:17 +00001480 // Introduce this template parameter's instantiation into the instantiation
1481 // scope.
1482 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1483
John McCalle29ba202009-08-20 01:44:21 +00001484 return Inst;
1485}
1486
Douglas Gregor33642df2009-10-23 23:25:44 +00001487Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1488 NonTypeTemplateParmDecl *D) {
1489 // Substitute into the type of the non-type template parameter.
1490 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001491 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001492 if (DI) {
1493 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1494 D->getDeclName());
1495 if (DI) T = DI->getType();
1496 } else {
1497 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1498 D->getDeclName());
1499 DI = 0;
1500 }
1501 if (T.isNull())
1502 return 0;
1503
1504 // Check that this type is acceptable for a non-type template parameter.
1505 bool Invalid = false;
1506 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1507 if (T.isNull()) {
1508 T = SemaRef.Context.IntTy;
1509 Invalid = true;
1510 }
1511
1512 NonTypeTemplateParmDecl *Param
1513 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001514 D->getDepth() - TemplateArgs.getNumLevels(),
1515 D->getPosition(), D->getIdentifier(), T,
1516 DI);
Douglas Gregor33642df2009-10-23 23:25:44 +00001517 if (Invalid)
1518 Param->setInvalidDecl();
1519
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001520 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001521
1522 // Introduce this template parameter's instantiation into the instantiation
1523 // scope.
1524 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001525 return Param;
1526}
1527
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001528Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001529TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1530 TemplateTemplateParmDecl *D) {
1531 // Instantiate the template parameter list of the template template parameter.
1532 TemplateParameterList *TempParams = D->getTemplateParameters();
1533 TemplateParameterList *InstParams;
1534 {
1535 // Perform the actual substitution of template parameters within a new,
1536 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001537 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001538 InstParams = SubstTemplateParams(TempParams);
1539 if (!InstParams)
1540 return NULL;
1541 }
1542
1543 // Build the template template parameter.
1544 TemplateTemplateParmDecl *Param
1545 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001546 D->getDepth() - TemplateArgs.getNumLevels(),
1547 D->getPosition(), D->getIdentifier(),
1548 InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001549 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001550
Douglas Gregor9106ef72009-11-11 16:58:32 +00001551 // Introduce this template parameter's instantiation into the instantiation
1552 // scope.
1553 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1554
1555 return Param;
1556}
1557
Douglas Gregor48c32a72009-11-17 06:07:40 +00001558Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1559 // Using directives are never dependent, so they require no explicit
1560
1561 UsingDirectiveDecl *Inst
1562 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1563 D->getNamespaceKeyLocation(),
1564 D->getQualifierRange(), D->getQualifier(),
1565 D->getIdentLocation(),
1566 D->getNominatedNamespace(),
1567 D->getCommonAncestor());
1568 Owner->addDecl(Inst);
1569 return Inst;
1570}
1571
John McCalled976492009-12-04 22:46:56 +00001572Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001573
1574 // The nested name specifier may be dependent, for example
1575 // template <typename T> struct t {
1576 // struct s1 { T f1(); };
1577 // struct s2 : s1 { using s1::f1; };
1578 // };
1579 // template struct t<int>;
1580 // Here, in using s1::f1, s1 refers to t<T>::s1;
1581 // we need to substitute for t<int>::s1.
1582 NestedNameSpecifier *NNS =
1583 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1584 D->getNestedNameRange(),
1585 TemplateArgs);
1586 if (!NNS)
1587 return 0;
1588
1589 // The name info is non-dependent, so no transformation
1590 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001591 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001592
John McCall9f54ad42009-12-10 09:41:52 +00001593 // We only need to do redeclaration lookups if we're in a class
1594 // scope (in fact, it's not really even possible in non-class
1595 // scopes).
1596 bool CheckRedeclaration = Owner->isRecord();
1597
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001598 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1599 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001600
John McCalled976492009-12-04 22:46:56 +00001601 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001602 D->getNestedNameRange(),
1603 D->getUsingLocation(),
Douglas Gregor1b398202010-09-29 17:58:28 +00001604 NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001605 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001606 D->isTypeName());
1607
1608 CXXScopeSpec SS;
Douglas Gregor1b398202010-09-29 17:58:28 +00001609 SS.setScopeRep(NNS);
John McCalled976492009-12-04 22:46:56 +00001610 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001611
1612 if (CheckRedeclaration) {
1613 Prev.setHideTags(false);
1614 SemaRef.LookupQualifiedName(Prev, Owner);
1615
1616 // Check for invalid redeclarations.
1617 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1618 D->isTypeName(), SS,
1619 D->getLocation(), Prev))
1620 NewUD->setInvalidDecl();
1621
1622 }
1623
1624 if (!NewUD->isInvalidDecl() &&
1625 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001626 D->getLocation()))
1627 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001628
John McCalled976492009-12-04 22:46:56 +00001629 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1630 NewUD->setAccess(D->getAccess());
1631 Owner->addDecl(NewUD);
1632
John McCall9f54ad42009-12-10 09:41:52 +00001633 // Don't process the shadow decls for an invalid decl.
1634 if (NewUD->isInvalidDecl())
1635 return NewUD;
1636
John McCall323c3102009-12-22 22:26:37 +00001637 bool isFunctionScope = Owner->isFunctionOrMethod();
1638
John McCall9f54ad42009-12-10 09:41:52 +00001639 // Process the shadow decls.
1640 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1641 I != E; ++I) {
1642 UsingShadowDecl *Shadow = *I;
1643 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001644 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1645 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001646 TemplateArgs));
1647
1648 if (CheckRedeclaration &&
1649 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1650 continue;
1651
1652 UsingShadowDecl *InstShadow
1653 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1654 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001655
1656 if (isFunctionScope)
1657 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001658 }
John McCalled976492009-12-04 22:46:56 +00001659
1660 return NewUD;
1661}
1662
1663Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001664 // Ignore these; we handle them in bulk when processing the UsingDecl.
1665 return 0;
John McCalled976492009-12-04 22:46:56 +00001666}
1667
John McCall7ba107a2009-11-18 02:36:19 +00001668Decl * TemplateDeclInstantiator
1669 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001670 NestedNameSpecifier *NNS =
1671 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1672 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001673 TemplateArgs);
1674 if (!NNS)
1675 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001677 CXXScopeSpec SS;
1678 SS.setRange(D->getTargetNestedNameRange());
1679 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001681 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1682 // Hence, no tranformation is required for it.
1683 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001684 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001685 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001686 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001687 /*instantiation*/ true,
1688 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001689 if (UD)
John McCalled976492009-12-04 22:46:56 +00001690 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1691
John McCall7ba107a2009-11-18 02:36:19 +00001692 return UD;
1693}
1694
1695Decl * TemplateDeclInstantiator
1696 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1697 NestedNameSpecifier *NNS =
1698 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1699 D->getTargetNestedNameRange(),
1700 TemplateArgs);
1701 if (!NNS)
1702 return 0;
1703
1704 CXXScopeSpec SS;
1705 SS.setRange(D->getTargetNestedNameRange());
1706 SS.setScopeRep(NNS);
1707
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001708 DeclarationNameInfo NameInfo
1709 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1710
John McCall7ba107a2009-11-18 02:36:19 +00001711 NamedDecl *UD =
1712 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001713 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001714 /*instantiation*/ true,
1715 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001716 if (UD)
John McCalled976492009-12-04 22:46:56 +00001717 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1718
Anders Carlsson0d8df782009-08-29 19:37:28 +00001719 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001720}
1721
John McCallce3ff2b2009-08-25 22:02:44 +00001722Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001723 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001724 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001725 if (D->isInvalidDecl())
1726 return 0;
1727
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001728 return Instantiator.Visit(D);
1729}
1730
John McCalle29ba202009-08-20 01:44:21 +00001731/// \brief Instantiates a nested template parameter list in the current
1732/// instantiation context.
1733///
1734/// \param L The parameter list to instantiate
1735///
1736/// \returns NULL if there was an error
1737TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001738TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001739 // Get errors for all the parameters before bailing out.
1740 bool Invalid = false;
1741
1742 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001743 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001744 ParamVector Params;
1745 Params.reserve(N);
1746 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1747 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001748 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001749 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001750 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001751 }
1752
1753 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001754 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001755 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001756
1757 TemplateParameterList *InstL
1758 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1759 L->getLAngleLoc(), &Params.front(), N,
1760 L->getRAngleLoc());
1761 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001762}
John McCalle29ba202009-08-20 01:44:21 +00001763
Douglas Gregored9c0f92009-10-29 00:04:11 +00001764/// \brief Instantiate the declaration of a class template partial
1765/// specialization.
1766///
1767/// \param ClassTemplate the (instantiated) class template that is partially
1768// specialized by the instantiation of \p PartialSpec.
1769///
1770/// \param PartialSpec the (uninstantiated) class template partial
1771/// specialization that we are instantiating.
1772///
Douglas Gregord65587f2010-11-10 19:44:59 +00001773/// \returns The instantiated partial specialization, if successful; otherwise,
1774/// NULL to indicate an error.
1775ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001776TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1777 ClassTemplateDecl *ClassTemplate,
1778 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001779 // Create a local instantiation scope for this class template partial
1780 // specialization, which will contain the instantiations of the template
1781 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001782 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001783
Douglas Gregored9c0f92009-10-29 00:04:11 +00001784 // Substitute into the template parameters of the class template partial
1785 // specialization.
1786 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1787 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1788 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001789 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001790
1791 // Substitute into the template arguments of the class template partial
1792 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001793 const TemplateArgumentLoc *PartialSpecTemplateArgs
1794 = PartialSpec->getTemplateArgsAsWritten();
1795 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1796
John McCalld5532b62009-11-23 01:53:49 +00001797 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001798 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001799 TemplateArgumentLoc Loc;
1800 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregord65587f2010-11-10 19:44:59 +00001801 return 0;
John McCalld5532b62009-11-23 01:53:49 +00001802 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001803 }
1804
1805
1806 // Check that the template argument list is well-formed for this
1807 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001808 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001809 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1810 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001811 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001812 false,
1813 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001814 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001815
1816 // Figure out where to insert this class template partial specialization
1817 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001818 void *InsertPos = 0;
1819 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001820 = ClassTemplate->findPartialSpecialization(Converted.data(),
1821 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001822
1823 // Build the canonical type that describes the converted template
1824 // arguments of the class template partial specialization.
1825 QualType CanonType
1826 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001827 Converted.data(),
1828 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001829
1830 // Build the fully-sugared type for this class template
1831 // specialization as the user wrote in the specialization
1832 // itself. This means that we'll pretty-print the type retrieved
1833 // from the specialization's declaration the way that the user
1834 // actually wrote the specialization, rather than formatting the
1835 // name based on the "canonical" representation used to store the
1836 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001837 TypeSourceInfo *WrittenTy
1838 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1839 TemplateName(ClassTemplate),
1840 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001841 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001842 CanonType);
1843
1844 if (PrevDecl) {
1845 // We've already seen a partial specialization with the same template
1846 // parameters and template arguments. This can happen, for example, when
1847 // substituting the outer template arguments ends up causing two
1848 // class template partial specializations of a member class template
1849 // to have identical forms, e.g.,
1850 //
1851 // template<typename T, typename U>
1852 // struct Outer {
1853 // template<typename X, typename Y> struct Inner;
1854 // template<typename Y> struct Inner<T, Y>;
1855 // template<typename Y> struct Inner<U, Y>;
1856 // };
1857 //
1858 // Outer<int, int> outer; // error: the partial specializations of Inner
1859 // // have the same signature.
1860 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001861 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001862 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1863 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001864 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001865 }
1866
1867
1868 // Create the class template partial specialization declaration.
1869 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001870 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1871 PartialSpec->getTagKind(),
1872 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001873 PartialSpec->getLocation(),
1874 InstParams,
1875 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001876 Converted.data(),
1877 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001878 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001879 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001880 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001881 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001882 // Substitute the nested name specifier, if any.
1883 if (SubstQualifier(PartialSpec, InstPartialSpec))
1884 return 0;
1885
Douglas Gregored9c0f92009-10-29 00:04:11 +00001886 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001887 InstPartialSpec->setTypeAsWritten(WrittenTy);
1888
Douglas Gregored9c0f92009-10-29 00:04:11 +00001889 // Add this partial specialization to the set of class template partial
1890 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001891 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001892 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001893}
1894
John McCall21ef0fa2010-03-11 09:03:00 +00001895TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001896TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001897 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001898 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1899 assert(OldTInfo && "substituting function without type source info");
1900 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001901 TypeSourceInfo *NewTInfo
1902 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1903 D->getTypeSpecStartLoc(),
1904 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001905 if (!NewTInfo)
1906 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001907
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001908 if (NewTInfo != OldTInfo) {
1909 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001910 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001911 if (FunctionProtoTypeLoc *OldProtoLoc
1912 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1913 TypeLoc NewTL = NewTInfo->getTypeLoc();
1914 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1915 assert(NewProtoLoc && "Missing prototype?");
1916 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1917 // FIXME: Variadic templates will break this.
1918 Params.push_back(NewProtoLoc->getArg(i));
1919 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001920 OldProtoLoc->getArg(i),
1921 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001922 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001923 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001924 } else {
1925 // The function type itself was not dependent and therefore no
1926 // substitution occurred. However, we still need to instantiate
1927 // the function parameters themselves.
1928 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001929 if (FunctionProtoTypeLoc *OldProtoLoc
1930 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1931 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1932 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1933 if (!Parm)
1934 return 0;
1935 Params.push_back(Parm);
1936 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001937 }
1938 }
John McCall21ef0fa2010-03-11 09:03:00 +00001939 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001940}
1941
Mike Stump1eb44332009-09-09 15:08:12 +00001942/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001943/// declaration (New) from the corresponding fields of its template (Tmpl).
1944///
1945/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001946bool
1947TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001948 FunctionDecl *Tmpl) {
1949 if (Tmpl->isDeleted())
1950 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Douglas Gregorcca9e962009-07-01 22:01:06 +00001952 // If we are performing substituting explicitly-specified template arguments
1953 // or deduced template arguments into a function template and we reach this
1954 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001955 // to keeping the new function template specialization. We therefore
1956 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001957 // into a template instantiation for this specific function template
1958 // specialization, which is not a SFINAE context, so that we diagnose any
1959 // further errors in the declaration itself.
1960 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1961 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1962 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1963 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001964 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001965 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001966 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001967 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001968 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001969 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1970 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001971 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001972 }
1973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001975 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1976 assert(Proto && "Function template without prototype?");
1977
1978 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1979 Proto->getNoReturnAttr()) {
1980 // The function has an exception specification or a "noreturn"
1981 // attribute. Substitute into each of the exception types.
1982 llvm::SmallVector<QualType, 4> Exceptions;
1983 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1984 // FIXME: Poor location information!
1985 QualType T
1986 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1987 New->getLocation(), New->getDeclName());
1988 if (T.isNull() ||
1989 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1990 continue;
1991
1992 Exceptions.push_back(T);
1993 }
1994
1995 // Rebuild the function type
1996
1997 const FunctionProtoType *NewProto
1998 = New->getType()->getAs<FunctionProtoType>();
1999 assert(NewProto && "Template instantiation without function prototype?");
2000 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2001 NewProto->arg_type_begin(),
2002 NewProto->getNumArgs(),
2003 NewProto->isVariadic(),
2004 NewProto->getTypeQuals(),
2005 Proto->hasExceptionSpec(),
2006 Proto->hasAnyExceptionSpec(),
2007 Exceptions.size(),
2008 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002009 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002010 }
2011
John McCall1d8d1cc2010-08-01 02:01:53 +00002012 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002013
Douglas Gregore53060f2009-06-25 22:08:12 +00002014 return false;
2015}
2016
Douglas Gregor5545e162009-03-24 00:38:23 +00002017/// \brief Initializes common fields of an instantiated method
2018/// declaration (New) from the corresponding fields of its template
2019/// (Tmpl).
2020///
2021/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002022bool
2023TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002024 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002025 if (InitFunctionInstantiation(New, Tmpl))
2026 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregor5545e162009-03-24 00:38:23 +00002028 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002029 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002030 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002031
2032 // FIXME: attributes
2033 // FIXME: New needs a pointer to Tmpl
2034 return false;
2035}
Douglas Gregora58861f2009-05-13 20:28:22 +00002036
2037/// \brief Instantiate the definition of the given function from its
2038/// template.
2039///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002040/// \param PointOfInstantiation the point at which the instantiation was
2041/// required. Note that this is not precisely a "point of instantiation"
2042/// for the function, but it's close.
2043///
Douglas Gregora58861f2009-05-13 20:28:22 +00002044/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002045/// function template specialization or member function of a class template
2046/// specialization.
2047///
2048/// \param Recursive if true, recursively instantiates any functions that
2049/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002050///
2051/// \param DefinitionRequired if true, then we are performing an explicit
2052/// instantiation where the body of the function is required. Complain if
2053/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002054void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002055 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002056 bool Recursive,
2057 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002058 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002059 return;
2060
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002061 // Never instantiate an explicit specialization.
2062 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2063 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002064
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002065 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002066 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002067 Stmt *Pattern = 0;
2068 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002069 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002070
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002071 if (!Pattern) {
2072 if (DefinitionRequired) {
2073 if (Function->getPrimaryTemplate())
2074 Diag(PointOfInstantiation,
2075 diag::err_explicit_instantiation_undefined_func_template)
2076 << Function->getPrimaryTemplate();
2077 else
2078 Diag(PointOfInstantiation,
2079 diag::err_explicit_instantiation_undefined_member)
2080 << 1 << Function->getDeclName() << Function->getDeclContext();
2081
2082 if (PatternDecl)
2083 Diag(PatternDecl->getLocation(),
2084 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002085 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002086 } else if (Function->getTemplateSpecializationKind()
2087 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002088 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002089 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002090 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002091
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002092 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002093 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002094
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002095 // C++0x [temp.explicit]p9:
2096 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002097 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002098 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002099 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002100 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002101 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002102 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002104 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2105 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002106 return;
2107
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002108 // If we're performing recursive template instantiation, create our own
2109 // queue of pending implicit instantiations that we will instantiate later,
2110 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002111 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002112 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002113 if (Recursive) {
2114 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002115 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002116 }
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Douglas Gregor9679caf2010-05-12 17:27:19 +00002118 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002119 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002120 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002121
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002122 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002123 // recorded, unless we're actually a member function within a local
2124 // class, in which case we need to merge our results with the parent
2125 // scope (of the enclosing function).
2126 bool MergeWithParentScope = false;
2127 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2128 MergeWithParentScope = Rec->isLocalClass();
2129
2130 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002132 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002133 // instantiation scope, and set the parameter names to those used
2134 // in the template.
2135 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2136 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2137 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2138 FunctionParam->setDeclName(PatternParam->getDeclName());
2139 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2140 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002141
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002142 // Enter the scope of this instantiation. We don't use
2143 // PushDeclContext because we don't have a scope.
2144 DeclContext *PreviousContext = CurContext;
2145 CurContext = Function;
2146
Mike Stump1eb44332009-09-09 15:08:12 +00002147 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002148 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002149
2150 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002151 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002152 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2153 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2154 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002155 }
2156
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002157 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002158 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002159
Douglas Gregor52604ab2009-09-11 21:19:12 +00002160 if (Body.isInvalid())
2161 Function->setInvalidDecl();
2162
John McCall9ae2f072010-08-23 23:25:46 +00002163 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002164 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002165
John McCall0c01d182010-03-24 05:22:00 +00002166 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2167
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002168 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002169
2170 DeclGroupRef DG(Function);
2171 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Douglas Gregor60406be2010-01-16 22:29:39 +00002173 // This class may have local implicit instantiations that need to be
2174 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002175 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002176 Scope.Exit();
2177
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002178 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002179 // Define any pending vtables.
2180 DefineUsedVTables();
2181
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002182 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002183 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002184 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002186 // Restore the set of pending vtables.
2187 VTableUses.swap(SavedVTableUses);
2188
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002189 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002190 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002191 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002192}
2193
2194/// \brief Instantiate the definition of the given variable from its
2195/// template.
2196///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002197/// \param PointOfInstantiation the point at which the instantiation was
2198/// required. Note that this is not precisely a "point of instantiation"
2199/// for the function, but it's close.
2200///
2201/// \param Var the already-instantiated declaration of a static member
2202/// variable of a class template specialization.
2203///
2204/// \param Recursive if true, recursively instantiates any functions that
2205/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002206///
2207/// \param DefinitionRequired if true, then we are performing an explicit
2208/// instantiation where an out-of-line definition of the member variable
2209/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002210void Sema::InstantiateStaticDataMemberDefinition(
2211 SourceLocation PointOfInstantiation,
2212 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002213 bool Recursive,
2214 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002215 if (Var->isInvalidDecl())
2216 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Douglas Gregor7caa6822009-07-24 20:34:43 +00002218 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002219 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002220 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002221 assert(Def->isStaticDataMember() && "Not a static data member?");
2222 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Douglas Gregor0d035142009-10-27 18:42:08 +00002224 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002225 // We did not find an out-of-line definition of this static data member,
2226 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002227 // instantiate this definition (or provide a specialization for it) in
2228 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002229 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002230 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002231 Diag(PointOfInstantiation,
2232 diag::err_explicit_instantiation_undefined_member)
2233 << 2 << Var->getDeclName() << Var->getDeclContext();
2234 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002235 } else if (Var->getTemplateSpecializationKind()
2236 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002237 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002238 std::make_pair(Var, PointOfInstantiation));
2239 }
2240
Douglas Gregor7caa6822009-07-24 20:34:43 +00002241 return;
2242 }
2243
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002244 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002245 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002246 return;
2247
2248 // C++0x [temp.explicit]p9:
2249 // Except for inline functions, other explicit instantiation declarations
2250 // have the effect of suppressing the implicit instantiation of the entity
2251 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002252 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002253 == TSK_ExplicitInstantiationDeclaration)
2254 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Douglas Gregor7caa6822009-07-24 20:34:43 +00002256 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2257 if (Inst)
2258 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Douglas Gregor7caa6822009-07-24 20:34:43 +00002260 // If we're performing recursive template instantiation, create our own
2261 // queue of pending implicit instantiations that we will instantiate later,
2262 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002263 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002264 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002265 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Douglas Gregor7caa6822009-07-24 20:34:43 +00002267 // Enter the scope of this instantiation. We don't use
2268 // PushDeclContext because we don't have a scope.
2269 DeclContext *PreviousContext = CurContext;
2270 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002272 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002273 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002274 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002275 CurContext = PreviousContext;
2276
2277 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002278 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2279 assert(MSInfo && "Missing member specialization information?");
2280 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2281 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002282 DeclGroupRef DG(Var);
2283 Consumer.HandleTopLevelDecl(DG);
2284 }
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Douglas Gregor7caa6822009-07-24 20:34:43 +00002286 if (Recursive) {
2287 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002288 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002289 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Douglas Gregor7caa6822009-07-24 20:34:43 +00002291 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002292 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002293 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002294}
Douglas Gregor815215d2009-05-27 05:35:12 +00002295
Anders Carlsson09025312009-08-29 05:16:22 +00002296void
2297Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2298 const CXXConstructorDecl *Tmpl,
2299 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Anders Carlsson09025312009-08-29 05:16:22 +00002301 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002302 bool AnyErrors = false;
2303
Anders Carlsson09025312009-08-29 05:16:22 +00002304 // Instantiate all the initializers.
2305 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002306 InitsEnd = Tmpl->init_end();
2307 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002308 CXXBaseOrMemberInitializer *Init = *Inits;
2309
Chandler Carruth030ef472010-09-03 21:54:20 +00002310 // Only instantiate written initializers, let Sema re-construct implicit
2311 // ones.
2312 if (!Init->isWritten())
2313 continue;
2314
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002315 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002316 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002318 // Instantiate the initializer.
2319 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002320 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002321 AnyErrors = true;
2322 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002323 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002324
Anders Carlsson09025312009-08-29 05:16:22 +00002325 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002326 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002327 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002328 TemplateArgs,
2329 Init->getSourceLocation(),
2330 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002331 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002332 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002333 New->setInvalidDecl();
2334 continue;
2335 }
2336
John McCalla93c9342009-12-07 02:54:59 +00002337 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002338 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002339 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002340 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002341 Init->getRParenLoc(),
2342 New->getParent());
2343 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002344 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002346 // Is this an anonymous union?
2347 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002348 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2349 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002350 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002351 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2352 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002353 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002354
2355 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002356 NewArgs.size(),
2357 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002358 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002359 Init->getRParenLoc());
2360 }
2361
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002362 if (NewInit.isInvalid()) {
2363 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002364 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002365 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002366 // FIXME: It would be nice if ASTOwningVector had a release function.
2367 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Anders Carlsson09025312009-08-29 05:16:22 +00002369 NewInits.push_back((MemInitTy *)NewInit.get());
2370 }
2371 }
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Anders Carlsson09025312009-08-29 05:16:22 +00002373 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002374 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002375 /*FIXME: ColonLoc */
2376 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002377 NewInits.data(), NewInits.size(),
2378 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002379}
2380
John McCall52a575a2009-08-29 08:11:13 +00002381// TODO: this could be templated if the various decl types used the
2382// same method name.
2383static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2384 ClassTemplateDecl *Instance) {
2385 Pattern = Pattern->getCanonicalDecl();
2386
2387 do {
2388 Instance = Instance->getCanonicalDecl();
2389 if (Pattern == Instance) return true;
2390 Instance = Instance->getInstantiatedFromMemberTemplate();
2391 } while (Instance);
2392
2393 return false;
2394}
2395
Douglas Gregor0d696532009-09-28 06:34:35 +00002396static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2397 FunctionTemplateDecl *Instance) {
2398 Pattern = Pattern->getCanonicalDecl();
2399
2400 do {
2401 Instance = Instance->getCanonicalDecl();
2402 if (Pattern == Instance) return true;
2403 Instance = Instance->getInstantiatedFromMemberTemplate();
2404 } while (Instance);
2405
2406 return false;
2407}
2408
Douglas Gregored9c0f92009-10-29 00:04:11 +00002409static bool
2410isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2411 ClassTemplatePartialSpecializationDecl *Instance) {
2412 Pattern
2413 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2414 do {
2415 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2416 Instance->getCanonicalDecl());
2417 if (Pattern == Instance)
2418 return true;
2419 Instance = Instance->getInstantiatedFromMember();
2420 } while (Instance);
2421
2422 return false;
2423}
2424
John McCall52a575a2009-08-29 08:11:13 +00002425static bool isInstantiationOf(CXXRecordDecl *Pattern,
2426 CXXRecordDecl *Instance) {
2427 Pattern = Pattern->getCanonicalDecl();
2428
2429 do {
2430 Instance = Instance->getCanonicalDecl();
2431 if (Pattern == Instance) return true;
2432 Instance = Instance->getInstantiatedFromMemberClass();
2433 } while (Instance);
2434
2435 return false;
2436}
2437
2438static bool isInstantiationOf(FunctionDecl *Pattern,
2439 FunctionDecl *Instance) {
2440 Pattern = Pattern->getCanonicalDecl();
2441
2442 do {
2443 Instance = Instance->getCanonicalDecl();
2444 if (Pattern == Instance) return true;
2445 Instance = Instance->getInstantiatedFromMemberFunction();
2446 } while (Instance);
2447
2448 return false;
2449}
2450
2451static bool isInstantiationOf(EnumDecl *Pattern,
2452 EnumDecl *Instance) {
2453 Pattern = Pattern->getCanonicalDecl();
2454
2455 do {
2456 Instance = Instance->getCanonicalDecl();
2457 if (Pattern == Instance) return true;
2458 Instance = Instance->getInstantiatedFromMemberEnum();
2459 } while (Instance);
2460
2461 return false;
2462}
2463
John McCalled976492009-12-04 22:46:56 +00002464static bool isInstantiationOf(UsingShadowDecl *Pattern,
2465 UsingShadowDecl *Instance,
2466 ASTContext &C) {
2467 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2468}
2469
2470static bool isInstantiationOf(UsingDecl *Pattern,
2471 UsingDecl *Instance,
2472 ASTContext &C) {
2473 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2474}
2475
John McCall7ba107a2009-11-18 02:36:19 +00002476static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2477 UsingDecl *Instance,
2478 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002479 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002480}
2481
2482static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002483 UsingDecl *Instance,
2484 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002485 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002486}
2487
John McCall52a575a2009-08-29 08:11:13 +00002488static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2489 VarDecl *Instance) {
2490 assert(Instance->isStaticDataMember());
2491
2492 Pattern = Pattern->getCanonicalDecl();
2493
2494 do {
2495 Instance = Instance->getCanonicalDecl();
2496 if (Pattern == Instance) return true;
2497 Instance = Instance->getInstantiatedFromStaticDataMember();
2498 } while (Instance);
2499
2500 return false;
2501}
2502
John McCalled976492009-12-04 22:46:56 +00002503// Other is the prospective instantiation
2504// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002505static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002506 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002507 if (UnresolvedUsingTypenameDecl *UUD
2508 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2509 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2510 return isInstantiationOf(UUD, UD, Ctx);
2511 }
2512 }
2513
2514 if (UnresolvedUsingValueDecl *UUD
2515 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002516 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2517 return isInstantiationOf(UUD, UD, Ctx);
2518 }
2519 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002520
Anders Carlsson0d8df782009-08-29 19:37:28 +00002521 return false;
2522 }
Mike Stump1eb44332009-09-09 15:08:12 +00002523
John McCall52a575a2009-08-29 08:11:13 +00002524 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2525 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002526
John McCall52a575a2009-08-29 08:11:13 +00002527 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2528 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002529
John McCall52a575a2009-08-29 08:11:13 +00002530 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2531 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002532
Douglas Gregor7caa6822009-07-24 20:34:43 +00002533 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002534 if (Var->isStaticDataMember())
2535 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2536
2537 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2538 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002539
Douglas Gregor0d696532009-09-28 06:34:35 +00002540 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2541 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2542
Douglas Gregored9c0f92009-10-29 00:04:11 +00002543 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2544 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2545 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2546 PartialSpec);
2547
Anders Carlssond8b285f2009-09-01 04:26:58 +00002548 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2549 if (!Field->getDeclName()) {
2550 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002551 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002552 cast<FieldDecl>(D);
2553 }
2554 }
Mike Stump1eb44332009-09-09 15:08:12 +00002555
John McCalled976492009-12-04 22:46:56 +00002556 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2557 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2558
2559 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2560 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2561
Douglas Gregor815215d2009-05-27 05:35:12 +00002562 return D->getDeclName() && isa<NamedDecl>(Other) &&
2563 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2564}
2565
2566template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002567static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002568 NamedDecl *D,
2569 ForwardIterator first,
2570 ForwardIterator last) {
2571 for (; first != last; ++first)
2572 if (isInstantiationOf(Ctx, D, *first))
2573 return cast<NamedDecl>(*first);
2574
2575 return 0;
2576}
2577
John McCall02cace72009-08-28 07:59:38 +00002578/// \brief Finds the instantiation of the given declaration context
2579/// within the current instantiation.
2580///
2581/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002582DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002583 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002584 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002585 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002586 return cast_or_null<DeclContext>(ID);
2587 } else return DC;
2588}
2589
Douglas Gregored961e72009-05-27 17:54:46 +00002590/// \brief Find the instantiation of the given declaration within the
2591/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002592///
2593/// This routine is intended to be used when \p D is a declaration
2594/// referenced from within a template, that needs to mapped into the
2595/// corresponding declaration within an instantiation. For example,
2596/// given:
2597///
2598/// \code
2599/// template<typename T>
2600/// struct X {
2601/// enum Kind {
2602/// KnownValue = sizeof(T)
2603/// };
2604///
2605/// bool getKind() const { return KnownValue; }
2606/// };
2607///
2608/// template struct X<int>;
2609/// \endcode
2610///
2611/// In the instantiation of X<int>::getKind(), we need to map the
2612/// EnumConstantDecl for KnownValue (which refers to
2613/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002614/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2615/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002616NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002617 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002618 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002619 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002620 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002621 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002622 // D is a local of some kind. Look into the map of local
2623 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002624 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002625 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002626
Douglas Gregore95b4092009-09-16 18:34:49 +00002627 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2628 if (!Record->isDependentContext())
2629 return D;
2630
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002631 // If the RecordDecl is actually the injected-class-name or a
2632 // "templated" declaration for a class template, class template
2633 // partial specialization, or a member class of a class template,
2634 // substitute into the injected-class-name of the class template
2635 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002636 QualType T;
2637 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2638
2639 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002640 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002641 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2642 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002643 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002644
2645 // If we call SubstType with an InjectedClassNameType here we
2646 // can end up in an infinite loop.
2647 T = Context.getTypeDeclType(Record);
2648 assert(isa<InjectedClassNameType>(T) &&
2649 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002650 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002651 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002652
2653 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002654 // Substitute into the injected-class-name to get the type
2655 // corresponding to the instantiation we want, which may also be
2656 // the current instantiation (if we're in a template
2657 // definition). This substitution should never fail, since we
2658 // know we can instantiate the injected-class-name or we
2659 // wouldn't have gotten to the injected-class-name!
2660
2661 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2662 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002663 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2664 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2665
2666 if (!T->isDependentType()) {
2667 assert(T->isRecordType() && "Instantiation must produce a record type");
2668 return T->getAs<RecordType>()->getDecl();
2669 }
2670
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002671 // We are performing "partial" template instantiation to create
2672 // the member declarations for the members of a class template
2673 // specialization. Therefore, D is actually referring to something
2674 // in the current instantiation. Look through the current
2675 // context, which contains actual instantiations, to find the
2676 // instantiation of the "current instantiation" that D refers
2677 // to.
2678 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002679 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002680 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002681 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002682 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002683 if (isInstantiationOf(ClassTemplate,
2684 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002685 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002686
2687 if (!DC->isDependentContext())
2688 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002689 }
2690
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002691 // We're performing "instantiation" of a member of the current
2692 // instantiation while we are type-checking the
2693 // definition. Compute the declaration context and return that.
2694 assert(!SawNonDependentContext &&
2695 "No dependent context while instantiating record");
2696 DeclContext *DC = computeDeclContext(T);
2697 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002698 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002699 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002700 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002701
Douglas Gregore95b4092009-09-16 18:34:49 +00002702 // Fall through to deal with other dependent record types (e.g.,
2703 // anonymous unions in class templates).
2704 }
John McCall52a575a2009-08-29 08:11:13 +00002705
Douglas Gregore95b4092009-09-16 18:34:49 +00002706 if (!ParentDC->isDependentContext())
2707 return D;
2708
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002709 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002710 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002711 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Douglas Gregor815215d2009-05-27 05:35:12 +00002713 if (ParentDC != D->getDeclContext()) {
2714 // We performed some kind of instantiation in the parent context,
2715 // so now we need to look into the instantiated parent context to
2716 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002717
John McCall3cb0ebd2010-03-10 03:28:59 +00002718 // If our context used to be dependent, we may need to instantiate
2719 // it before performing lookup into that context.
2720 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002721 if (!Spec->isDependentContext()) {
2722 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002723 const RecordType *Tag = T->getAs<RecordType>();
2724 assert(Tag && "type of non-dependent record is not a RecordType");
2725 if (!Tag->isBeingDefined() &&
2726 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2727 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00002728
2729 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002730 }
2731 }
2732
Douglas Gregor815215d2009-05-27 05:35:12 +00002733 NamedDecl *Result = 0;
2734 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002735 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002736 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2737 } else {
2738 // Since we don't have a name for the entity we're looking for,
2739 // our only option is to walk through all of the declarations to
2740 // find that name. This will occur in a few cases:
2741 //
2742 // - anonymous struct/union within a template
2743 // - unnamed class/struct/union/enum within a template
2744 //
2745 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002746 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002747 ParentDC->decls_begin(),
2748 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002749 }
Mike Stump1eb44332009-09-09 15:08:12 +00002750
John McCall9f54ad42009-12-10 09:41:52 +00002751 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002752 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2753 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002754 && "Unable to find instantiation of declaration!");
2755
Douglas Gregor815215d2009-05-27 05:35:12 +00002756 D = Result;
2757 }
2758
Douglas Gregor815215d2009-05-27 05:35:12 +00002759 return D;
2760}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002761
Mike Stump1eb44332009-09-09 15:08:12 +00002762/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002763/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002764void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002765 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00002766 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002767 PendingImplicitInstantiation Inst;
2768
2769 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002770 Inst = PendingInstantiations.front();
2771 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00002772 } else {
2773 Inst = PendingLocalImplicitInstantiations.front();
2774 PendingLocalImplicitInstantiations.pop_front();
2775 }
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Douglas Gregor7caa6822009-07-24 20:34:43 +00002777 // Instantiate function definitions
2778 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00002779 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
2780 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00002781 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
2782 TSK_ExplicitInstantiationDefinition;
2783 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
2784 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002785 continue;
2786 }
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Douglas Gregor7caa6822009-07-24 20:34:43 +00002788 // Instantiate static data member definitions.
2789 VarDecl *Var = cast<VarDecl>(Inst.first);
2790 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002791
Chandler Carruth291b4412010-02-13 10:17:50 +00002792 // Don't try to instantiate declarations if the most recent redeclaration
2793 // is invalid.
2794 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2795 continue;
2796
2797 // Check if the most recent declaration has changed the specialization kind
2798 // and removed the need for implicit instantiation.
2799 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2800 case TSK_Undeclared:
2801 assert(false && "Cannot instantitiate an undeclared specialization.");
2802 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00002803 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00002804 continue; // No longer need to instantiate this type.
2805 case TSK_ExplicitInstantiationDefinition:
2806 // We only need an instantiation if the pending instantiation *is* the
2807 // explicit instantiation.
2808 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00002809 case TSK_ImplicitInstantiation:
2810 break;
2811 }
2812
John McCallf312b1e2010-08-26 23:41:50 +00002813 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
2814 "instantiating static data member "
2815 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Chandler Carruth58e390e2010-08-25 08:27:02 +00002817 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
2818 TSK_ExplicitInstantiationDefinition;
2819 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
2820 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002821 }
2822}
John McCall0c01d182010-03-24 05:22:00 +00002823
2824void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2825 const MultiLevelTemplateArgumentList &TemplateArgs) {
2826 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2827 E = Pattern->ddiag_end(); I != E; ++I) {
2828 DependentDiagnostic *DD = *I;
2829
2830 switch (DD->getKind()) {
2831 case DependentDiagnostic::Access:
2832 HandleDependentAccessCheck(*DD, TemplateArgs);
2833 break;
2834 }
2835 }
2836}