blob: 6b5713a2fa2ddc84c1f1f7a28937c9041dbbb21c [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 Gregor6b98b2e2010-03-02 07:38:39 +0000169/// \brief Instantiate an initializer, breaking it into separate
170/// initialization arguments.
171///
172/// \param S The semantic analysis object.
173///
174/// \param Init The initializer to instantiate.
175///
176/// \param TemplateArgs Template arguments to be substituted into the
177/// initializer.
178///
179/// \param NewArgs Will be filled in with the instantiation arguments.
180///
181/// \returns true if an error occurred, false otherwise
182static bool InstantiateInitializer(Sema &S, Expr *Init,
183 const MultiLevelTemplateArgumentList &TemplateArgs,
184 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000185 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000186 SourceLocation &RParenLoc) {
187 NewArgs.clear();
188 LParenLoc = SourceLocation();
189 RParenLoc = SourceLocation();
190
191 if (!Init)
192 return false;
193
John McCall4765fa02010-12-06 08:20:24 +0000194 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000195 Init = ExprTemp->getSubExpr();
196
197 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
198 Init = Binder->getSubExpr();
199
200 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
201 Init = ICE->getSubExprAsWritten();
202
203 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
204 LParenLoc = ParenList->getLParenLoc();
205 RParenLoc = ParenList->getRParenLoc();
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000206 return S.SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
207 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000208 }
209
210 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000211 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000212 if (S.SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
213 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000214 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000215
Douglas Gregor28329e52010-03-24 21:22:47 +0000216 // FIXME: Fake locations!
217 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000218 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000219 return false;
220 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000221 }
222
John McCall60d7b3a2010-08-24 06:29:42 +0000223 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000224 if (Result.isInvalid())
225 return true;
226
227 NewArgs.push_back(Result.takeAs<Expr>());
228 return false;
229}
230
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000231Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000232 // If this is the variable for an anonymous struct or union,
233 // instantiate the anonymous struct/union type first.
234 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
235 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
236 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
237 return 0;
238
John McCallce3ff2b2009-08-25 22:02:44 +0000239 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000240 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000241 TemplateArgs,
242 D->getTypeSpecStartLoc(),
243 D->getDeclName());
244 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000245 return 0;
246
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000247 if (DI->getType()->isFunctionType()) {
248 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
249 << D->isStaticDataMember() << DI->getType();
250 return 0;
251 }
252
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000253 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000254 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
255 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000256 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000257 D->getStorageClass(),
258 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000259 Var->setThreadSpecified(D->isThreadSpecified());
260 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000261
John McCallb6217662010-03-15 10:12:16 +0000262 // Substitute the nested name specifier, if any.
263 if (SubstQualifier(D, Var))
264 return 0;
265
Mike Stump1eb44332009-09-09 15:08:12 +0000266 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000267 // out-of-line, the instantiation will have the same lexical
268 // context (which will be a namespace scope) as the template.
269 if (D->isOutOfLine())
270 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000271
John McCall46460a62010-01-20 21:53:11 +0000272 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000273
274 if (!D->isStaticDataMember())
275 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000276
Mike Stump390b4cc2009-05-16 07:39:55 +0000277 // FIXME: In theory, we could have a previous declaration for variables that
278 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000279 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000280 // FIXME: having to fake up a LookupResult is dumb.
281 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000282 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000283 if (D->isStaticDataMember())
284 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000285 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Douglas Gregor7caa6822009-07-24 20:34:43 +0000287 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000288 if (!D->isStaticDataMember())
289 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000290 Owner->makeDeclVisibleInContext(Var);
291 } else {
292 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000293 if (Owner->isFunctionOrMethod())
294 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000295 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000296 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000297
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000298 // Link instantiations of static data members back to the template from
299 // which they were instantiated.
300 if (Var->isStaticDataMember())
301 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000302 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000303
Douglas Gregor60c93c92010-02-09 07:26:29 +0000304 if (Var->getAnyInitializer()) {
305 // We already have an initializer in the class.
306 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000307 if (Var->isStaticDataMember() && !D->isOutOfLine())
308 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
309 else
310 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
311
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000312 // Instantiate the initializer.
313 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000314 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000315 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000316 InitArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000317 // Attach the initializer to the declaration.
318 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000319 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000320 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000321 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000322 move_arg(InitArgs),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000323 RParenLoc);
324 } else if (InitArgs.size() == 1) {
John McCall9ae2f072010-08-23 23:25:46 +0000325 Expr *Init = InitArgs.take()[0];
326 SemaRef.AddInitializerToDecl(Var, Init, false);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000327 } else {
328 assert(InitArgs.size() == 0);
John McCalld226f652010-08-21 09:40:31 +0000329 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000330 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000331 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000332 // FIXME: Not too happy about invalidating the declaration
333 // because of a bogus initializer.
334 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000335 }
336
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000337 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000338 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000339 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000340
Douglas Gregor5764f612010-05-08 23:05:03 +0000341 // Diagnose unused local variables.
342 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
343 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000344
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000345 return Var;
346}
347
Abramo Bagnara6206d532010-06-05 05:09:32 +0000348Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
349 AccessSpecDecl* AD
350 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
351 D->getAccessSpecifierLoc(), D->getColonLoc());
352 Owner->addHiddenDecl(AD);
353 return AD;
354}
355
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000356Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
357 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000358 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000359 if (DI->getType()->isDependentType() ||
360 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000361 DI = SemaRef.SubstType(DI, TemplateArgs,
362 D->getLocation(), D->getDeclName());
363 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000364 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000365 Invalid = true;
366 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000367 // C++ [temp.arg.type]p3:
368 // If a declaration acquires a function type through a type
369 // dependent on a template-parameter and this causes a
370 // declaration that does not use the syntactic form of a
371 // function declarator to have function type, the program is
372 // ill-formed.
373 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000374 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000375 Invalid = true;
376 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000377 } else {
378 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000379 }
380
381 Expr *BitWidth = D->getBitWidth();
382 if (Invalid)
383 BitWidth = 0;
384 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000385 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000386 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000387
John McCall60d7b3a2010-08-24 06:29:42 +0000388 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000389 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000390 if (InstantiatedBitWidth.isInvalid()) {
391 Invalid = true;
392 BitWidth = 0;
393 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000394 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000395 }
396
John McCall07fb6be2009-10-22 23:33:21 +0000397 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
398 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000399 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000400 D->getLocation(),
401 D->isMutable(),
402 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000403 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000404 D->getAccess(),
405 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000406 if (!Field) {
407 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000408 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
John McCall1d8d1cc2010-08-01 02:01:53 +0000411 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000412
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000413 if (Invalid)
414 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000416 if (!Field->getDeclName()) {
417 // Keep track of where this decl came from.
418 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000419 }
420 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
421 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000422 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000423 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000426 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000427 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000428 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000429
430 return Field;
431}
432
Francois Pichet87c2e122010-11-21 06:08:52 +0000433Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
434 NamedDecl **NamedChain =
435 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
436
437 int i = 0;
438 for (IndirectFieldDecl::chain_iterator PI =
439 D->chain_begin(), PE = D->chain_end();
440 PI != PE; ++PI)
441 NamedChain[i++] = (SemaRef.FindInstantiatedDecl(D->getLocation(),
442 *PI, TemplateArgs));
443
Francois Pichet40e17752010-12-09 10:07:54 +0000444 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000445 IndirectFieldDecl* IndirectField
446 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000447 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000448 NamedChain, D->getChainingSize());
449
450
451 IndirectField->setImplicit(D->isImplicit());
452 IndirectField->setAccess(D->getAccess());
453 Owner->addDecl(IndirectField);
454 return IndirectField;
455}
456
John McCall02cace72009-08-28 07:59:38 +0000457Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000458 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000459 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000460 if (TypeSourceInfo *Ty = D->getFriendType()) {
461 TypeSourceInfo *InstTy =
462 SemaRef.SubstType(Ty, TemplateArgs,
463 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000464 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000465 return 0;
John McCall02cace72009-08-28 07:59:38 +0000466
Douglas Gregor06245bf2010-04-07 17:57:12 +0000467 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
468 if (!FD)
469 return 0;
470
471 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000472 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000473 Owner->addDecl(FD);
474 return FD;
475 }
476
477 NamedDecl *ND = D->getFriendDecl();
478 assert(ND && "friend decl must be a decl or a type!");
479
John McCallaf2094e2010-04-08 09:05:18 +0000480 // All of the Visit implementations for the various potential friend
481 // declarations have to be carefully written to work for friend
482 // objects, with the most important detail being that the target
483 // decl should almost certainly not be placed in Owner.
484 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000485 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000486
John McCall02cace72009-08-28 07:59:38 +0000487 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000488 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
489 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000490 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000491 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000492 Owner->addDecl(FD);
493 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000494}
495
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000496Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
497 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregorac7610d2009-06-22 20:57:11 +0000499 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000500 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000501
John McCall60d7b3a2010-08-24 06:29:42 +0000502 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000503 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000504 if (InstantiatedAssertExpr.isInvalid())
505 return 0;
506
John McCall60d7b3a2010-08-24 06:29:42 +0000507 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000508 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000509 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000510 InstantiatedAssertExpr.get(),
511 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000512}
513
514Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000515 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000516 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000517 D->getTagKeywordLoc(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000518 /*PrevDecl=*/0, D->isScoped(),
519 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000520 if (D->isFixed()) {
521 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
522 // If we have type source information for the underlying type, it means it
523 // has been explicitly set by the user. Perform substitution on it before
524 // moving on.
525 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
526 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
527 TemplateArgs,
528 UnderlyingLoc,
529 DeclarationName()));
530
531 if (!Enum->getIntegerTypeSourceInfo())
532 Enum->setIntegerType(SemaRef.Context.IntTy);
533 }
534 else {
535 assert(!D->getIntegerType()->isDependentType()
536 && "Dependent type without type source info");
537 Enum->setIntegerType(D->getIntegerType());
538 }
539 }
540
John McCall5b629aa2010-10-22 23:36:17 +0000541 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
542
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000543 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000544 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000545 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000546 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000547 Enum->startDefinition();
548
Douglas Gregor96084f12010-03-01 19:00:07 +0000549 if (D->getDeclContext()->isFunctionOrMethod())
550 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
551
John McCalld226f652010-08-21 09:40:31 +0000552 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000553
554 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000555 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
556 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000557 EC != ECEnd; ++EC) {
558 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000559 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000560 if (Expr *UninstValue = EC->getInitExpr()) {
561 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000562 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000563 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000564
John McCallce3ff2b2009-08-25 22:02:44 +0000565 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000566 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000567
568 // Drop the initial value and continue.
569 bool isInvalid = false;
570 if (Value.isInvalid()) {
571 Value = SemaRef.Owned((Expr *)0);
572 isInvalid = true;
573 }
574
Mike Stump1eb44332009-09-09 15:08:12 +0000575 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000576 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
577 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000578 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000579
580 if (isInvalid) {
581 if (EnumConst)
582 EnumConst->setInvalidDecl();
583 Enum->setInvalidDecl();
584 }
585
586 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000587 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
588
John McCall3b85ecf2010-01-23 22:37:59 +0000589 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000590 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000591 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000592 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000593
594 if (D->getDeclContext()->isFunctionOrMethod()) {
595 // If the enumeration is within a function or method, record the enum
596 // constant as a local.
597 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
598 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000599 }
600 }
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000602 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000603 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000604 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000605 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000606 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000607 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000608
609 return Enum;
610}
611
Douglas Gregor6477b692009-03-25 15:04:13 +0000612Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
613 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
614 return 0;
615}
616
John McCalle29ba202009-08-20 01:44:21 +0000617Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000618 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
619
Douglas Gregor550d9b22009-10-31 17:21:17 +0000620 // Create a local instantiation scope for this class template, which
621 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000622 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000623 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000624 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000625 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000626 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000627
628 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000629
630 // Instantiate the qualifier. We have to do this first in case
631 // we're a friend declaration, because if we are then we need to put
632 // the new declaration in the appropriate context.
633 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
634 if (Qualifier) {
635 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
636 Pattern->getQualifierRange(),
637 TemplateArgs);
638 if (!Qualifier) return 0;
639 }
640
641 CXXRecordDecl *PrevDecl = 0;
642 ClassTemplateDecl *PrevClassTemplate = 0;
643
Nick Lewycky37574f52010-11-08 23:29:42 +0000644 if (!isFriend && Pattern->getPreviousDeclaration()) {
645 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
646 if (Found.first != Found.second) {
647 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
648 if (PrevClassTemplate)
649 PrevDecl = PrevClassTemplate->getTemplatedDecl();
650 }
651 }
652
John McCall93ba8572010-03-25 06:39:04 +0000653 // If this isn't a friend, then it's a member template, in which
654 // case we just want to build the instantiation in the
655 // specialization. If it is a friend, we want to build it in
656 // the appropriate context.
657 DeclContext *DC = Owner;
658 if (isFriend) {
659 if (Qualifier) {
660 CXXScopeSpec SS;
661 SS.setScopeRep(Qualifier);
662 SS.setRange(Pattern->getQualifierRange());
663 DC = SemaRef.computeDeclContext(SS);
664 if (!DC) return 0;
665 } else {
666 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
667 Pattern->getDeclContext(),
668 TemplateArgs);
669 }
670
671 // Look for a previous declaration of the template in the owning
672 // context.
673 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
674 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
675 SemaRef.LookupQualifiedName(R, DC);
676
677 if (R.isSingleResult()) {
678 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
679 if (PrevClassTemplate)
680 PrevDecl = PrevClassTemplate->getTemplatedDecl();
681 }
682
683 if (!PrevClassTemplate && Qualifier) {
684 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000685 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
686 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000687 return 0;
688 }
689
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000690 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000691 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000692 bool Complain = true;
693
694 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
695 // template for struct std::tr1::__detail::_Map_base, where the
696 // template parameters of the friend declaration don't match the
697 // template parameters of the original declaration. In this one
698 // case, we don't complain about the ill-formed friend
699 // declaration.
700 if (isFriend && Pattern->getIdentifier() &&
701 Pattern->getIdentifier()->isStr("_Map_base") &&
702 DC->isNamespace() &&
703 cast<NamespaceDecl>(DC)->getIdentifier() &&
704 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
705 DeclContext *DCParent = DC->getParent();
706 if (DCParent->isNamespace() &&
707 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
708 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
709 DeclContext *DCParent2 = DCParent->getParent();
710 if (DCParent2->isNamespace() &&
711 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
712 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
713 DCParent2->getParent()->isTranslationUnit())
714 Complain = false;
715 }
716 }
717
John McCall93ba8572010-03-25 06:39:04 +0000718 TemplateParameterList *PrevParams
719 = PrevClassTemplate->getTemplateParameters();
720
721 // Make sure the parameter lists match.
722 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000723 Complain,
724 Sema::TPL_TemplateMatch)) {
725 if (Complain)
726 return 0;
727
728 AdoptedPreviousTemplateParams = true;
729 InstParams = PrevParams;
730 }
John McCall93ba8572010-03-25 06:39:04 +0000731
732 // Do some additional validation, then merge default arguments
733 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000734 if (!AdoptedPreviousTemplateParams &&
735 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000736 Sema::TPC_ClassTemplate))
737 return 0;
738 }
739 }
740
John McCalle29ba202009-08-20 01:44:21 +0000741 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000742 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000743 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000744 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000745 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000746
John McCall93ba8572010-03-25 06:39:04 +0000747 if (Qualifier)
748 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000749
John McCalle29ba202009-08-20 01:44:21 +0000750 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000751 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
752 D->getIdentifier(), InstParams, RecordInst,
753 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000754 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000755
John McCall93ba8572010-03-25 06:39:04 +0000756 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000757 if (PrevClassTemplate)
758 Inst->setAccess(PrevClassTemplate->getAccess());
759 else
760 Inst->setAccess(D->getAccess());
761
John McCall93ba8572010-03-25 06:39:04 +0000762 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
763 // TODO: do we want to track the instantiation progeny of this
764 // friend target decl?
765 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000766 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000767 if (!PrevClassTemplate)
768 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000769 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000770
771 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000772 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000773 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000774
Douglas Gregor259571e2009-10-30 22:42:42 +0000775 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000776 if (isFriend) {
777 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000778 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000779 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000780
John McCalle29ba202009-08-20 01:44:21 +0000781 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000782
783 if (!PrevClassTemplate) {
784 // Queue up any out-of-line partial specializations of this member
785 // class template; the client will force their instantiation once
786 // the enclosing class has been instantiated.
787 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
788 D->getPartialSpecializations(PartialSpecs);
789 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
790 if (PartialSpecs[I]->isOutOfLine())
791 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
792 }
793
John McCalle29ba202009-08-20 01:44:21 +0000794 return Inst;
795}
796
Douglas Gregord60e1052009-08-27 16:57:43 +0000797Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000798TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
799 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000800 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
801
802 // Lookup the already-instantiated declaration in the instantiation
803 // of the class template and return that.
804 DeclContext::lookup_result Found
805 = Owner->lookup(ClassTemplate->getDeclName());
806 if (Found.first == Found.second)
807 return 0;
808
809 ClassTemplateDecl *InstClassTemplate
810 = dyn_cast<ClassTemplateDecl>(*Found.first);
811 if (!InstClassTemplate)
812 return 0;
813
Douglas Gregord65587f2010-11-10 19:44:59 +0000814 if (ClassTemplatePartialSpecializationDecl *Result
815 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
816 return Result;
817
818 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000819}
820
821Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000822TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000823 // Create a local instantiation scope for this function template, which
824 // will contain the instantiations of the template parameters and then get
825 // merged with the local instantiation scope for the function template
826 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000827 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000828
Douglas Gregord60e1052009-08-27 16:57:43 +0000829 TemplateParameterList *TempParams = D->getTemplateParameters();
830 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000831 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000832 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000833
Douglas Gregora735b202009-10-13 14:39:41 +0000834 FunctionDecl *Instantiated = 0;
835 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
836 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
837 InstParams));
838 else
839 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
840 D->getTemplatedDecl(),
841 InstParams));
842
843 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000844 return 0;
845
John McCall46460a62010-01-20 21:53:11 +0000846 Instantiated->setAccess(D->getAccess());
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000849 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000850 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000851 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000852 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000853 assert(InstTemplate &&
854 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000855
John McCallb1a56e72010-03-26 23:10:15 +0000856 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
857
John McCalle976ffe2009-12-14 23:19:40 +0000858 // Link the instantiation back to the pattern *unless* this is a
859 // non-definition friend declaration.
860 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000861 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000862 InstTemplate->setInstantiatedFromMemberTemplate(D);
863
John McCallb1a56e72010-03-26 23:10:15 +0000864 // Make declarations visible in the appropriate context.
865 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000866 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000867
Douglas Gregord60e1052009-08-27 16:57:43 +0000868 return InstTemplate;
869}
870
Douglas Gregord475b8d2009-03-25 21:17:03 +0000871Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
872 CXXRecordDecl *PrevDecl = 0;
873 if (D->isInjectedClassName())
874 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000875 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000876 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
877 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000878 TemplateArgs);
879 if (!Prev) return 0;
880 PrevDecl = cast<CXXRecordDecl>(Prev);
881 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000882
883 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000884 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000885 D->getLocation(), D->getIdentifier(),
886 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000887
888 // Substitute the nested name specifier, if any.
889 if (SubstQualifier(D, Record))
890 return 0;
891
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000893 // FIXME: Check against AS_none is an ugly hack to work around the issue that
894 // the tag decls introduced by friend class declarations don't have an access
895 // specifier. Remove once this area of the code gets sorted out.
896 if (D->getAccess() != AS_none)
897 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000898 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000899 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000900
John McCall02cace72009-08-28 07:59:38 +0000901 // If the original function was part of a friend declaration,
902 // inherit its namespace state.
903 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
904 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
905
Douglas Gregor9901c572010-05-21 00:31:19 +0000906 // Make sure that anonymous structs and unions are recorded.
907 if (D->isAnonymousStructOrUnion()) {
908 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000909 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000910 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
911 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000912
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000913 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000914 return Record;
915}
916
John McCall02cace72009-08-28 07:59:38 +0000917/// Normal class members are of more specific types and therefore
918/// don't make it here. This function serves two purposes:
919/// 1) instantiating function templates
920/// 2) substituting friend declarations
921/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000922Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000923 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000924 // Check whether there is already a function template specialization for
925 // this declaration.
926 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
927 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000928 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000929 std::pair<const TemplateArgument *, unsigned> Innermost
930 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000932 FunctionDecl *SpecFunc
933 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
934 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor127102b2009-06-29 20:59:39 +0000936 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000937 if (SpecFunc)
938 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000939 }
Mike Stump1eb44332009-09-09 15:08:12 +0000940
John McCallb0cb0222010-03-27 05:57:59 +0000941 bool isFriend;
942 if (FunctionTemplate)
943 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
944 else
945 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
946
Douglas Gregor79c22782010-01-16 20:21:20 +0000947 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000948 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000949 !(isa<Decl>(Owner) &&
950 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000951 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Douglas Gregore53060f2009-06-25 22:08:12 +0000953 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000954 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
955 TInfo = SubstFunctionType(D, Params);
956 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000957 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000958 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000959
John McCalld325daa2010-03-26 04:53:08 +0000960 NestedNameSpecifier *Qualifier = D->getQualifier();
961 if (Qualifier) {
962 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
963 D->getQualifierRange(),
964 TemplateArgs);
965 if (!Qualifier) return 0;
966 }
967
John McCall68b6b872010-02-06 01:50:47 +0000968 // If we're instantiating a local function declaration, put the result
969 // in the owner; otherwise we need to find the instantiated context.
970 DeclContext *DC;
971 if (D->getDeclContext()->isFunctionOrMethod())
972 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000973 else if (isFriend && Qualifier) {
974 CXXScopeSpec SS;
975 SS.setScopeRep(Qualifier);
976 SS.setRange(D->getQualifierRange());
977 DC = SemaRef.computeDeclContext(SS);
978 if (!DC) return 0;
979 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000980 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
981 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000982 }
John McCall68b6b872010-02-06 01:50:47 +0000983
John McCall02cace72009-08-28 07:59:38 +0000984 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000985 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000986 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000987 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000988 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000989
John McCalld325daa2010-03-26 04:53:08 +0000990 if (Qualifier)
991 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000992
John McCallb1a56e72010-03-26 23:10:15 +0000993 DeclContext *LexicalDC = Owner;
994 if (!isFriend && D->isOutOfLine()) {
995 assert(D->getDeclContext()->isFileContext());
996 LexicalDC = D->getDeclContext();
997 }
998
999 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Douglas Gregore53060f2009-06-25 22:08:12 +00001001 // Attach the parameters
1002 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001003 if (Params[P])
1004 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001005 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001006
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001007 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001008 if (TemplateParams) {
1009 // Our resulting instantiation is actually a function template, since we
1010 // are substituting only the outer template parameters. For example, given
1011 //
1012 // template<typename T>
1013 // struct X {
1014 // template<typename U> friend void f(T, U);
1015 // };
1016 //
1017 // X<int> x;
1018 //
1019 // We are instantiating the friend function template "f" within X<int>,
1020 // which means substituting int for T, but leaving "f" as a friend function
1021 // template.
1022 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001023 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001024 Function->getLocation(),
1025 Function->getDeclName(),
1026 TemplateParams, Function);
1027 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001028
1029 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001030
1031 if (isFriend && D->isThisDeclarationADefinition()) {
1032 // TODO: should we remember this connection regardless of whether
1033 // the friend declaration provided a body?
1034 FunctionTemplate->setInstantiatedFromMemberTemplate(
1035 D->getDescribedFunctionTemplate());
1036 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001037 } else if (FunctionTemplate) {
1038 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001039 std::pair<const TemplateArgument *, unsigned> Innermost
1040 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001041 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001042 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001043 Innermost.first,
1044 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001045 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001046 } else if (isFriend && D->isThisDeclarationADefinition()) {
1047 // TODO: should we remember this connection regardless of whether
1048 // the friend declaration provided a body?
1049 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001050 }
Douglas Gregora735b202009-10-13 14:39:41 +00001051
Douglas Gregore53060f2009-06-25 22:08:12 +00001052 if (InitFunctionInstantiation(Function, D))
1053 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregore53060f2009-06-25 22:08:12 +00001055 bool Redeclaration = false;
1056 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001057 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001058
John McCall68263142009-11-18 22:49:29 +00001059 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1060 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1061
John McCallaf2094e2010-04-08 09:05:18 +00001062 if (DependentFunctionTemplateSpecializationInfo *Info
1063 = D->getDependentSpecializationInfo()) {
1064 assert(isFriend && "non-friend has dependent specialization info?");
1065
1066 // This needs to be set now for future sanity.
1067 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1068
1069 // Instantiate the explicit template arguments.
1070 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1071 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001072 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1073 ExplicitArgs, TemplateArgs))
1074 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001075
1076 // Map the candidate templates to their instantiations.
1077 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1078 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1079 Info->getTemplate(I),
1080 TemplateArgs);
1081 if (!Temp) return 0;
1082
1083 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1084 }
1085
1086 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1087 &ExplicitArgs,
1088 Previous))
1089 Function->setInvalidDecl();
1090
1091 isExplicitSpecialization = true;
1092
1093 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001094 // Look only into the namespace where the friend would be declared to
1095 // find a previous declaration. This is the innermost enclosing namespace,
1096 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001097 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001098
Douglas Gregora735b202009-10-13 14:39:41 +00001099 // In C++, the previous declaration we find might be a tag type
1100 // (class or enum). In this case, the new declaration will hide the
1101 // tag type. Note that this does does not apply if we're declaring a
1102 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001103 if (Previous.isSingleTagDecl())
1104 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001105 }
1106
John McCall9f54ad42009-12-10 09:41:52 +00001107 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001108 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001109 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001110
John McCall76d32642010-04-24 01:30:58 +00001111 NamedDecl *PrincipalDecl = (TemplateParams
1112 ? cast<NamedDecl>(FunctionTemplate)
1113 : Function);
1114
Douglas Gregora735b202009-10-13 14:39:41 +00001115 // If the original function was part of a friend declaration,
1116 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001117 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001118 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001119 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001120 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001121 else
Douglas Gregora735b202009-10-13 14:39:41 +00001122 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001123
1124 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1125 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001126
Gabor Greif77535df2010-08-30 22:25:56 +00001127 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001128
Douglas Gregor238058c2010-05-18 05:45:02 +00001129 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1130 D->isThisDeclarationADefinition()) {
1131 // Check for a function body.
1132 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001133 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001134 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1135 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1136 << Function->getDeclName();
1137 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1138 Function->setInvalidDecl();
1139 }
1140 // Check for redefinitions due to other instantiations of this or
1141 // a similar friend function.
1142 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1143 REnd = Function->redecls_end();
1144 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001145 if (*R == Function)
1146 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001147 switch (R->getFriendObjectKind()) {
1148 case Decl::FOK_None:
1149 if (!queuedInstantiation && R->isUsed(false)) {
1150 if (MemberSpecializationInfo *MSInfo
1151 = Function->getMemberSpecializationInfo()) {
1152 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1153 SourceLocation Loc = R->getLocation(); // FIXME
1154 MSInfo->setPointOfInstantiation(Loc);
1155 SemaRef.PendingLocalImplicitInstantiations.push_back(
1156 std::make_pair(Function, Loc));
1157 queuedInstantiation = true;
1158 }
1159 }
1160 }
1161 break;
1162 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001163 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001164 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001165 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001166 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1167 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001168 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001169 Function->setInvalidDecl();
1170 break;
1171 }
1172 }
1173 }
1174 }
Douglas Gregora735b202009-10-13 14:39:41 +00001175 }
1176
John McCall76d32642010-04-24 01:30:58 +00001177 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1178 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1179 PrincipalDecl->setNonMemberOperator();
1180
Douglas Gregore53060f2009-06-25 22:08:12 +00001181 return Function;
1182}
1183
Douglas Gregord60e1052009-08-27 16:57:43 +00001184Decl *
1185TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1186 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001187 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1188 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001189 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001190 // We are creating a function template specialization from a function
1191 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001192 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001193 std::pair<const TemplateArgument *, unsigned> Innermost
1194 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001196 FunctionDecl *SpecFunc
1197 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1198 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Douglas Gregor6b906862009-08-21 00:16:32 +00001200 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001201 if (SpecFunc)
1202 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001203 }
1204
John McCallb0cb0222010-03-27 05:57:59 +00001205 bool isFriend;
1206 if (FunctionTemplate)
1207 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1208 else
1209 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1210
Douglas Gregor79c22782010-01-16 20:21:20 +00001211 bool MergeWithParentScope = (TemplateParams != 0) ||
1212 !(isa<Decl>(Owner) &&
1213 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001214 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001215
John McCall4eab39f2010-10-19 02:26:41 +00001216 // Instantiate enclosing template arguments for friends.
1217 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1218 unsigned NumTempParamLists = 0;
1219 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1220 TempParamLists.set_size(NumTempParamLists);
1221 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1222 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1223 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1224 if (!InstParams)
1225 return NULL;
1226 TempParamLists[I] = InstParams;
1227 }
1228 }
1229
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001230 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001231 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1232 TInfo = SubstFunctionType(D, Params);
1233 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001234 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001235 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001236
Abramo Bagnara723df242010-12-14 22:11:44 +00001237 // \brief If the type of this function, after ignoring parentheses,
1238 // is not *directly* a function type, then we're instantiating a function
1239 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001240 //
1241 // typedef int functype(int, int);
1242 // functype func;
1243 //
1244 // In this case, we'll just go instantiate the ParmVarDecls that we
1245 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001246 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001247 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001248 llvm::SmallVector<QualType, 4> ParamTypes;
1249 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1250 D->getNumParams(), TemplateArgs, ParamTypes,
1251 &Params))
1252 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001253 }
1254
John McCallb0cb0222010-03-27 05:57:59 +00001255 NestedNameSpecifier *Qualifier = D->getQualifier();
1256 if (Qualifier) {
1257 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1258 D->getQualifierRange(),
1259 TemplateArgs);
1260 if (!Qualifier) return 0;
1261 }
1262
1263 DeclContext *DC = Owner;
1264 if (isFriend) {
1265 if (Qualifier) {
1266 CXXScopeSpec SS;
1267 SS.setScopeRep(Qualifier);
1268 SS.setRange(D->getQualifierRange());
1269 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001270
1271 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1272 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001273 } else {
1274 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1275 D->getDeclContext(),
1276 TemplateArgs);
1277 }
1278 if (!DC) return 0;
1279 }
1280
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001281 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001282 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001283 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Abramo Bagnara25777432010-08-11 22:01:17 +00001285 DeclarationNameInfo NameInfo
1286 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001287 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001288 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001289 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001290 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001291 Constructor->isInlineSpecified(),
1292 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001293 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001294 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Craig Silversteinb41d8992010-10-21 00:44:50 +00001295 NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001296 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001297 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001298 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001299 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001300 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001301 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001302 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001303 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001304 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1305 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001306 D->isStatic(),
1307 D->getStorageClassAsWritten(),
1308 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001309 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001310
John McCallb0cb0222010-03-27 05:57:59 +00001311 if (Qualifier)
1312 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001313
Douglas Gregord60e1052009-08-27 16:57:43 +00001314 if (TemplateParams) {
1315 // Our resulting instantiation is actually a function template, since we
1316 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001317 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001318 // template<typename T>
1319 // struct X {
1320 // template<typename U> void f(T, U);
1321 // };
1322 //
1323 // X<int> x;
1324 //
1325 // We are instantiating the member template "f" within X<int>, which means
1326 // substituting int for T, but leaving "f" as a member function template.
1327 // Build the function template itself.
1328 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1329 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001330 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001331 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001332 if (isFriend) {
1333 FunctionTemplate->setLexicalDeclContext(Owner);
1334 FunctionTemplate->setObjectOfFriendDecl(true);
1335 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001336 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001337 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001338 } else if (FunctionTemplate) {
1339 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001340 std::pair<const TemplateArgument *, unsigned> Innermost
1341 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001342 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001343 TemplateArgumentList::CreateCopy(SemaRef.Context,
1344 Innermost.first,
1345 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001346 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001347 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001348 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001349 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001350 }
1351
Mike Stump1eb44332009-09-09 15:08:12 +00001352 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001353 // out-of-line, the instantiation will have the same lexical
1354 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001355 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001356 if (NumTempParamLists)
1357 Method->setTemplateParameterListsInfo(SemaRef.Context,
1358 NumTempParamLists,
1359 TempParamLists.data());
1360
John McCallb0cb0222010-03-27 05:57:59 +00001361 Method->setLexicalDeclContext(Owner);
1362 Method->setObjectOfFriendDecl(true);
1363 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001364 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Douglas Gregor5545e162009-03-24 00:38:23 +00001366 // Attach the parameters
1367 for (unsigned P = 0; P < Params.size(); ++P)
1368 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001369 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001370
1371 if (InitMethodInstantiation(Method, D))
1372 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001373
Abramo Bagnara25777432010-08-11 22:01:17 +00001374 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1375 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
John McCallb0cb0222010-03-27 05:57:59 +00001377 if (!FunctionTemplate || TemplateParams || isFriend) {
1378 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Douglas Gregordec06662009-08-21 18:42:58 +00001380 // In C++, the previous declaration we find might be a tag type
1381 // (class or enum). In this case, the new declaration will hide the
1382 // tag type. Note that this does does not apply if we're declaring a
1383 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001384 if (Previous.isSingleTagDecl())
1385 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001386 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001387
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001388 bool Redeclaration = false;
1389 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001390 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001391 /*FIXME:*/OverloadableAttrRequired);
1392
Douglas Gregor4ba31362009-12-01 17:24:26 +00001393 if (D->isPure())
1394 SemaRef.CheckPureMethod(Method, SourceRange());
1395
John McCall46460a62010-01-20 21:53:11 +00001396 Method->setAccess(D->getAccess());
1397
John McCallb0cb0222010-03-27 05:57:59 +00001398 if (FunctionTemplate) {
1399 // If there's a function template, let our caller handle it.
1400 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1401 // Don't hide a (potentially) valid declaration with an invalid one.
1402 } else {
1403 NamedDecl *DeclToAdd = (TemplateParams
1404 ? cast<NamedDecl>(FunctionTemplate)
1405 : Method);
1406 if (isFriend)
1407 Record->makeDeclVisibleInContext(DeclToAdd);
1408 else
1409 Owner->addDecl(DeclToAdd);
1410 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001411
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001412 return Method;
1413}
1414
Douglas Gregor615c5d42009-03-24 16:43:20 +00001415Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001416 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001417}
1418
Douglas Gregor03b2b072009-03-24 00:15:49 +00001419Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001420 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001421}
1422
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001423Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001424 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001425}
1426
Douglas Gregor6477b692009-03-25 15:04:13 +00001427ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001428 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001429}
1430
John McCalle29ba202009-08-20 01:44:21 +00001431Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1432 TemplateTypeParmDecl *D) {
1433 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001434 const Type* T = D->getTypeForDecl();
1435 assert(T->isTemplateTypeParmType());
1436 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001437
John McCalle29ba202009-08-20 01:44:21 +00001438 TemplateTypeParmDecl *Inst =
1439 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001440 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001441 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001442 D->wasDeclaredWithTypename(),
1443 D->isParameterPack());
1444
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001445 if (D->hasDefaultArgument())
1446 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001447
Douglas Gregor550d9b22009-10-31 17:21:17 +00001448 // Introduce this template parameter's instantiation into the instantiation
1449 // scope.
1450 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1451
John McCalle29ba202009-08-20 01:44:21 +00001452 return Inst;
1453}
1454
Douglas Gregor33642df2009-10-23 23:25:44 +00001455Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1456 NonTypeTemplateParmDecl *D) {
1457 // Substitute into the type of the non-type template parameter.
1458 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001459 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001460 if (DI) {
1461 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1462 D->getDeclName());
1463 if (DI) T = DI->getType();
1464 } else {
1465 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1466 D->getDeclName());
1467 DI = 0;
1468 }
1469 if (T.isNull())
1470 return 0;
1471
1472 // Check that this type is acceptable for a non-type template parameter.
1473 bool Invalid = false;
1474 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1475 if (T.isNull()) {
1476 T = SemaRef.Context.IntTy;
1477 Invalid = true;
1478 }
1479
Douglas Gregor10738d32010-12-23 23:51:58 +00001480 // FIXME: Variadic templates.
Douglas Gregor33642df2009-10-23 23:25:44 +00001481 NonTypeTemplateParmDecl *Param
1482 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001483 D->getDepth() - TemplateArgs.getNumLevels(),
1484 D->getPosition(), D->getIdentifier(), T,
Douglas Gregor10738d32010-12-23 23:51:58 +00001485 D->isParameterPack(), DI);
Douglas Gregor33642df2009-10-23 23:25:44 +00001486 if (Invalid)
1487 Param->setInvalidDecl();
1488
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001489 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001490
1491 // Introduce this template parameter's instantiation into the instantiation
1492 // scope.
1493 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001494 return Param;
1495}
1496
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001497Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001498TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1499 TemplateTemplateParmDecl *D) {
1500 // Instantiate the template parameter list of the template template parameter.
1501 TemplateParameterList *TempParams = D->getTemplateParameters();
1502 TemplateParameterList *InstParams;
1503 {
1504 // Perform the actual substitution of template parameters within a new,
1505 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001506 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001507 InstParams = SubstTemplateParams(TempParams);
1508 if (!InstParams)
1509 return NULL;
1510 }
1511
1512 // Build the template template parameter.
1513 TemplateTemplateParmDecl *Param
1514 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001515 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001516 D->getPosition(), D->isParameterPack(),
1517 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001518 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001519
Douglas Gregor9106ef72009-11-11 16:58:32 +00001520 // Introduce this template parameter's instantiation into the instantiation
1521 // scope.
1522 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1523
1524 return Param;
1525}
1526
Douglas Gregor48c32a72009-11-17 06:07:40 +00001527Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1528 // Using directives are never dependent, so they require no explicit
1529
1530 UsingDirectiveDecl *Inst
1531 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1532 D->getNamespaceKeyLocation(),
1533 D->getQualifierRange(), D->getQualifier(),
1534 D->getIdentLocation(),
1535 D->getNominatedNamespace(),
1536 D->getCommonAncestor());
1537 Owner->addDecl(Inst);
1538 return Inst;
1539}
1540
John McCalled976492009-12-04 22:46:56 +00001541Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001542
1543 // The nested name specifier may be dependent, for example
1544 // template <typename T> struct t {
1545 // struct s1 { T f1(); };
1546 // struct s2 : s1 { using s1::f1; };
1547 // };
1548 // template struct t<int>;
1549 // Here, in using s1::f1, s1 refers to t<T>::s1;
1550 // we need to substitute for t<int>::s1.
1551 NestedNameSpecifier *NNS =
1552 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1553 D->getNestedNameRange(),
1554 TemplateArgs);
1555 if (!NNS)
1556 return 0;
1557
1558 // The name info is non-dependent, so no transformation
1559 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001560 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001561
John McCall9f54ad42009-12-10 09:41:52 +00001562 // We only need to do redeclaration lookups if we're in a class
1563 // scope (in fact, it's not really even possible in non-class
1564 // scopes).
1565 bool CheckRedeclaration = Owner->isRecord();
1566
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001567 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1568 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001569
John McCalled976492009-12-04 22:46:56 +00001570 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001571 D->getNestedNameRange(),
1572 D->getUsingLocation(),
Douglas Gregor1b398202010-09-29 17:58:28 +00001573 NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001574 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001575 D->isTypeName());
1576
1577 CXXScopeSpec SS;
Douglas Gregor1b398202010-09-29 17:58:28 +00001578 SS.setScopeRep(NNS);
John McCalled976492009-12-04 22:46:56 +00001579 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001580
1581 if (CheckRedeclaration) {
1582 Prev.setHideTags(false);
1583 SemaRef.LookupQualifiedName(Prev, Owner);
1584
1585 // Check for invalid redeclarations.
1586 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1587 D->isTypeName(), SS,
1588 D->getLocation(), Prev))
1589 NewUD->setInvalidDecl();
1590
1591 }
1592
1593 if (!NewUD->isInvalidDecl() &&
1594 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001595 D->getLocation()))
1596 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001597
John McCalled976492009-12-04 22:46:56 +00001598 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1599 NewUD->setAccess(D->getAccess());
1600 Owner->addDecl(NewUD);
1601
John McCall9f54ad42009-12-10 09:41:52 +00001602 // Don't process the shadow decls for an invalid decl.
1603 if (NewUD->isInvalidDecl())
1604 return NewUD;
1605
John McCall323c3102009-12-22 22:26:37 +00001606 bool isFunctionScope = Owner->isFunctionOrMethod();
1607
John McCall9f54ad42009-12-10 09:41:52 +00001608 // Process the shadow decls.
1609 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1610 I != E; ++I) {
1611 UsingShadowDecl *Shadow = *I;
1612 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001613 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1614 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001615 TemplateArgs));
1616
1617 if (CheckRedeclaration &&
1618 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1619 continue;
1620
1621 UsingShadowDecl *InstShadow
1622 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1623 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001624
1625 if (isFunctionScope)
1626 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001627 }
John McCalled976492009-12-04 22:46:56 +00001628
1629 return NewUD;
1630}
1631
1632Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001633 // Ignore these; we handle them in bulk when processing the UsingDecl.
1634 return 0;
John McCalled976492009-12-04 22:46:56 +00001635}
1636
John McCall7ba107a2009-11-18 02:36:19 +00001637Decl * TemplateDeclInstantiator
1638 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001639 NestedNameSpecifier *NNS =
1640 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1641 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001642 TemplateArgs);
1643 if (!NNS)
1644 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001646 CXXScopeSpec SS;
1647 SS.setRange(D->getTargetNestedNameRange());
1648 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001650 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1651 // Hence, no tranformation is required for it.
1652 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001653 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001654 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001655 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001656 /*instantiation*/ true,
1657 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001658 if (UD)
John McCalled976492009-12-04 22:46:56 +00001659 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1660
John McCall7ba107a2009-11-18 02:36:19 +00001661 return UD;
1662}
1663
1664Decl * TemplateDeclInstantiator
1665 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1666 NestedNameSpecifier *NNS =
1667 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1668 D->getTargetNestedNameRange(),
1669 TemplateArgs);
1670 if (!NNS)
1671 return 0;
1672
1673 CXXScopeSpec SS;
1674 SS.setRange(D->getTargetNestedNameRange());
1675 SS.setScopeRep(NNS);
1676
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001677 DeclarationNameInfo NameInfo
1678 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1679
John McCall7ba107a2009-11-18 02:36:19 +00001680 NamedDecl *UD =
1681 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001682 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001683 /*instantiation*/ true,
1684 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001685 if (UD)
John McCalled976492009-12-04 22:46:56 +00001686 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1687
Anders Carlsson0d8df782009-08-29 19:37:28 +00001688 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001689}
1690
John McCallce3ff2b2009-08-25 22:02:44 +00001691Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001692 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001693 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001694 if (D->isInvalidDecl())
1695 return 0;
1696
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001697 return Instantiator.Visit(D);
1698}
1699
John McCalle29ba202009-08-20 01:44:21 +00001700/// \brief Instantiates a nested template parameter list in the current
1701/// instantiation context.
1702///
1703/// \param L The parameter list to instantiate
1704///
1705/// \returns NULL if there was an error
1706TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001707TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001708 // Get errors for all the parameters before bailing out.
1709 bool Invalid = false;
1710
1711 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001712 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001713 ParamVector Params;
1714 Params.reserve(N);
1715 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1716 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001717 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001718 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001719 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001720 }
1721
1722 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001723 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001724 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001725
1726 TemplateParameterList *InstL
1727 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1728 L->getLAngleLoc(), &Params.front(), N,
1729 L->getRAngleLoc());
1730 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001731}
John McCalle29ba202009-08-20 01:44:21 +00001732
Douglas Gregored9c0f92009-10-29 00:04:11 +00001733/// \brief Instantiate the declaration of a class template partial
1734/// specialization.
1735///
1736/// \param ClassTemplate the (instantiated) class template that is partially
1737// specialized by the instantiation of \p PartialSpec.
1738///
1739/// \param PartialSpec the (uninstantiated) class template partial
1740/// specialization that we are instantiating.
1741///
Douglas Gregord65587f2010-11-10 19:44:59 +00001742/// \returns The instantiated partial specialization, if successful; otherwise,
1743/// NULL to indicate an error.
1744ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001745TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1746 ClassTemplateDecl *ClassTemplate,
1747 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001748 // Create a local instantiation scope for this class template partial
1749 // specialization, which will contain the instantiations of the template
1750 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001751 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001752
Douglas Gregored9c0f92009-10-29 00:04:11 +00001753 // Substitute into the template parameters of the class template partial
1754 // specialization.
1755 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1756 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1757 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001758 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001759
1760 // Substitute into the template arguments of the class template partial
1761 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001762 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001763 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1764 PartialSpec->getNumTemplateArgsAsWritten(),
1765 InstTemplateArgs, TemplateArgs))
1766 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001767
Douglas Gregored9c0f92009-10-29 00:04:11 +00001768 // Check that the template argument list is well-formed for this
1769 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001770 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001771 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1772 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001773 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001774 false,
1775 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001776 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001777
1778 // Figure out where to insert this class template partial specialization
1779 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001780 void *InsertPos = 0;
1781 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001782 = ClassTemplate->findPartialSpecialization(Converted.data(),
1783 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001784
1785 // Build the canonical type that describes the converted template
1786 // arguments of the class template partial specialization.
1787 QualType CanonType
1788 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001789 Converted.data(),
1790 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001791
1792 // Build the fully-sugared type for this class template
1793 // specialization as the user wrote in the specialization
1794 // itself. This means that we'll pretty-print the type retrieved
1795 // from the specialization's declaration the way that the user
1796 // actually wrote the specialization, rather than formatting the
1797 // name based on the "canonical" representation used to store the
1798 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001799 TypeSourceInfo *WrittenTy
1800 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1801 TemplateName(ClassTemplate),
1802 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001803 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001804 CanonType);
1805
1806 if (PrevDecl) {
1807 // We've already seen a partial specialization with the same template
1808 // parameters and template arguments. This can happen, for example, when
1809 // substituting the outer template arguments ends up causing two
1810 // class template partial specializations of a member class template
1811 // to have identical forms, e.g.,
1812 //
1813 // template<typename T, typename U>
1814 // struct Outer {
1815 // template<typename X, typename Y> struct Inner;
1816 // template<typename Y> struct Inner<T, Y>;
1817 // template<typename Y> struct Inner<U, Y>;
1818 // };
1819 //
1820 // Outer<int, int> outer; // error: the partial specializations of Inner
1821 // // have the same signature.
1822 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001823 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001824 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1825 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001826 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001827 }
1828
1829
1830 // Create the class template partial specialization declaration.
1831 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001832 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1833 PartialSpec->getTagKind(),
1834 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001835 PartialSpec->getLocation(),
1836 InstParams,
1837 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001838 Converted.data(),
1839 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001840 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001841 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001842 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001843 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001844 // Substitute the nested name specifier, if any.
1845 if (SubstQualifier(PartialSpec, InstPartialSpec))
1846 return 0;
1847
Douglas Gregored9c0f92009-10-29 00:04:11 +00001848 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001849 InstPartialSpec->setTypeAsWritten(WrittenTy);
1850
Douglas Gregored9c0f92009-10-29 00:04:11 +00001851 // Add this partial specialization to the set of class template partial
1852 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001853 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001854 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001855}
1856
John McCall21ef0fa2010-03-11 09:03:00 +00001857TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001858TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001859 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001860 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1861 assert(OldTInfo && "substituting function without type source info");
1862 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001863 TypeSourceInfo *NewTInfo
1864 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1865 D->getTypeSpecStartLoc(),
1866 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001867 if (!NewTInfo)
1868 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001869
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001870 if (NewTInfo != OldTInfo) {
1871 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001872 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001873 if (FunctionProtoTypeLoc *OldProtoLoc
1874 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001875 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001876 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1877 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001878 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
1879 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
1880 OldIdx != NumOldParams; ++OldIdx) {
1881 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
1882 if (!OldParam->isParameterPack() ||
1883 (NewIdx < NumNewParams &&
1884 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
1885 // Simple case: normal parameter, or a parameter pack that's
1886 // instantiated to a (still-dependent) parameter pack.
1887 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
1888 Params.push_back(NewParam);
1889 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
1890 NewParam);
1891 continue;
1892 }
1893
1894 // Parameter pack: make the instantiation an argument pack.
1895 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
1896 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00001897 unsigned NumArgumentsInExpansion
1898 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
1899 TemplateArgs);
1900 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00001901 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
1902 Params.push_back(NewParam);
1903 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
1904 NewParam);
1905 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001906 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001907 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001908 } else {
1909 // The function type itself was not dependent and therefore no
1910 // substitution occurred. However, we still need to instantiate
1911 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001912 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001913 if (FunctionProtoTypeLoc *OldProtoLoc
1914 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1915 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1916 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1917 if (!Parm)
1918 return 0;
1919 Params.push_back(Parm);
1920 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001921 }
1922 }
John McCall21ef0fa2010-03-11 09:03:00 +00001923 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001924}
1925
Mike Stump1eb44332009-09-09 15:08:12 +00001926/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001927/// declaration (New) from the corresponding fields of its template (Tmpl).
1928///
1929/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001930bool
1931TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001932 FunctionDecl *Tmpl) {
1933 if (Tmpl->isDeleted())
1934 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Douglas Gregorcca9e962009-07-01 22:01:06 +00001936 // If we are performing substituting explicitly-specified template arguments
1937 // or deduced template arguments into a function template and we reach this
1938 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001939 // to keeping the new function template specialization. We therefore
1940 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001941 // into a template instantiation for this specific function template
1942 // specialization, which is not a SFINAE context, so that we diagnose any
1943 // further errors in the declaration itself.
1944 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1945 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1946 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1947 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001948 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001949 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001950 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001951 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001952 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001953 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1954 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001955 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001956 }
1957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001959 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1960 assert(Proto && "Function template without prototype?");
1961
1962 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1963 Proto->getNoReturnAttr()) {
1964 // The function has an exception specification or a "noreturn"
1965 // attribute. Substitute into each of the exception types.
1966 llvm::SmallVector<QualType, 4> Exceptions;
1967 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1968 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00001969 if (const PackExpansionType *PackExpansion
1970 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
1971 // We have a pack expansion. Instantiate it.
1972 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1973 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
1974 Unexpanded);
1975 assert(!Unexpanded.empty() &&
1976 "Pack expansion without parameter packs?");
1977
1978 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001979 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00001980 llvm::Optional<unsigned> NumExpansions
1981 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00001982 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
1983 SourceRange(),
1984 Unexpanded.data(),
1985 Unexpanded.size(),
1986 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00001987 Expand,
1988 RetainExpansion,
1989 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00001990 break;
1991
1992 if (!Expand) {
1993 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00001994 // just substitute into the pattern and create a new pack expansion
1995 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00001996 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1997 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
1998 TemplateArgs,
1999 New->getLocation(), New->getDeclName());
2000 if (T.isNull())
2001 break;
2002
Douglas Gregorcded4f62011-01-14 17:04:44 +00002003 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002004 Exceptions.push_back(T);
2005 continue;
2006 }
2007
2008 // Substitute into the pack expansion pattern for each template
2009 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002010 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002011 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2012
2013 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2014 TemplateArgs,
2015 New->getLocation(), New->getDeclName());
2016 if (T.isNull()) {
2017 Invalid = true;
2018 break;
2019 }
2020
2021 Exceptions.push_back(T);
2022 }
2023
2024 if (Invalid)
2025 break;
2026
2027 continue;
2028 }
2029
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002030 QualType T
2031 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2032 New->getLocation(), New->getDeclName());
2033 if (T.isNull() ||
2034 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2035 continue;
2036
2037 Exceptions.push_back(T);
2038 }
2039
2040 // Rebuild the function type
2041
John McCalle23cf432010-12-14 08:05:40 +00002042 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2043 EPI.HasExceptionSpec = Proto->hasExceptionSpec();
2044 EPI.HasAnyExceptionSpec = Proto->hasAnyExceptionSpec();
2045 EPI.NumExceptions = Exceptions.size();
2046 EPI.Exceptions = Exceptions.data();
2047 EPI.ExtInfo = Proto->getExtInfo();
2048
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002049 const FunctionProtoType *NewProto
2050 = New->getType()->getAs<FunctionProtoType>();
2051 assert(NewProto && "Template instantiation without function prototype?");
2052 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2053 NewProto->arg_type_begin(),
2054 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002055 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002056 }
2057
John McCall1d8d1cc2010-08-01 02:01:53 +00002058 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002059
Douglas Gregore53060f2009-06-25 22:08:12 +00002060 return false;
2061}
2062
Douglas Gregor5545e162009-03-24 00:38:23 +00002063/// \brief Initializes common fields of an instantiated method
2064/// declaration (New) from the corresponding fields of its template
2065/// (Tmpl).
2066///
2067/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002068bool
2069TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002070 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002071 if (InitFunctionInstantiation(New, Tmpl))
2072 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Douglas Gregor5545e162009-03-24 00:38:23 +00002074 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002075 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002076 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002077
2078 // FIXME: attributes
2079 // FIXME: New needs a pointer to Tmpl
2080 return false;
2081}
Douglas Gregora58861f2009-05-13 20:28:22 +00002082
2083/// \brief Instantiate the definition of the given function from its
2084/// template.
2085///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002086/// \param PointOfInstantiation the point at which the instantiation was
2087/// required. Note that this is not precisely a "point of instantiation"
2088/// for the function, but it's close.
2089///
Douglas Gregora58861f2009-05-13 20:28:22 +00002090/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002091/// function template specialization or member function of a class template
2092/// specialization.
2093///
2094/// \param Recursive if true, recursively instantiates any functions that
2095/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002096///
2097/// \param DefinitionRequired if true, then we are performing an explicit
2098/// instantiation where the body of the function is required. Complain if
2099/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002100void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002101 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002102 bool Recursive,
2103 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002104 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002105 return;
2106
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002107 // Never instantiate an explicit specialization.
2108 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2109 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002110
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002111 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002112 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002113 Stmt *Pattern = 0;
2114 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002115 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002116
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002117 if (!Pattern) {
2118 if (DefinitionRequired) {
2119 if (Function->getPrimaryTemplate())
2120 Diag(PointOfInstantiation,
2121 diag::err_explicit_instantiation_undefined_func_template)
2122 << Function->getPrimaryTemplate();
2123 else
2124 Diag(PointOfInstantiation,
2125 diag::err_explicit_instantiation_undefined_member)
2126 << 1 << Function->getDeclName() << Function->getDeclContext();
2127
2128 if (PatternDecl)
2129 Diag(PatternDecl->getLocation(),
2130 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002131 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002132 } else if (Function->getTemplateSpecializationKind()
2133 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002134 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002135 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002136 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002137
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002138 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002139 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002140
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002141 // C++0x [temp.explicit]p9:
2142 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002143 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002144 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002145 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002146 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002147 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002148 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002150 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2151 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002152 return;
2153
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002154 // If we're performing recursive template instantiation, create our own
2155 // queue of pending implicit instantiations that we will instantiate later,
2156 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002157 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002158 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002159 if (Recursive) {
2160 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002161 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Douglas Gregor9679caf2010-05-12 17:27:19 +00002164 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002165 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002166 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002167
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002168 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002169 // recorded, unless we're actually a member function within a local
2170 // class, in which case we need to merge our results with the parent
2171 // scope (of the enclosing function).
2172 bool MergeWithParentScope = false;
2173 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2174 MergeWithParentScope = Rec->isLocalClass();
2175
2176 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002178 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002179 // instantiation scope, and set the parameter names to those used
2180 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002181 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002182 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2183 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002184 if (!PatternParam->isParameterPack()) {
2185 // Simple case: not a parameter pack.
2186 assert(FParamIdx < Function->getNumParams());
2187 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2188 FunctionParam->setDeclName(PatternParam->getDeclName());
2189 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2190 ++FParamIdx;
2191 continue;
2192 }
2193
2194 // Expand the parameter pack.
2195 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2196 for (unsigned NumFParams = Function->getNumParams();
2197 FParamIdx < NumFParams;
2198 ++FParamIdx) {
2199 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2200 FunctionParam->setDeclName(PatternParam->getDeclName());
2201 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2202 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002203 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002204
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002205 // Enter the scope of this instantiation. We don't use
2206 // PushDeclContext because we don't have a scope.
2207 DeclContext *PreviousContext = CurContext;
2208 CurContext = Function;
2209
Mike Stump1eb44332009-09-09 15:08:12 +00002210 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002211 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002212
2213 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002214 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002215 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2216 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2217 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002218 }
2219
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002220 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002221 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002222
Douglas Gregor52604ab2009-09-11 21:19:12 +00002223 if (Body.isInvalid())
2224 Function->setInvalidDecl();
2225
John McCall9ae2f072010-08-23 23:25:46 +00002226 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002227 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002228
John McCall0c01d182010-03-24 05:22:00 +00002229 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2230
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002231 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002232
2233 DeclGroupRef DG(Function);
2234 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregor60406be2010-01-16 22:29:39 +00002236 // This class may have local implicit instantiations that need to be
2237 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002238 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002239 Scope.Exit();
2240
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002241 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002242 // Define any pending vtables.
2243 DefineUsedVTables();
2244
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002245 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002246 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002247 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002249 // Restore the set of pending vtables.
2250 VTableUses.swap(SavedVTableUses);
2251
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002252 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002253 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002254 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002255}
2256
2257/// \brief Instantiate the definition of the given variable from its
2258/// template.
2259///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002260/// \param PointOfInstantiation the point at which the instantiation was
2261/// required. Note that this is not precisely a "point of instantiation"
2262/// for the function, but it's close.
2263///
2264/// \param Var the already-instantiated declaration of a static member
2265/// variable of a class template specialization.
2266///
2267/// \param Recursive if true, recursively instantiates any functions that
2268/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002269///
2270/// \param DefinitionRequired if true, then we are performing an explicit
2271/// instantiation where an out-of-line definition of the member variable
2272/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002273void Sema::InstantiateStaticDataMemberDefinition(
2274 SourceLocation PointOfInstantiation,
2275 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002276 bool Recursive,
2277 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002278 if (Var->isInvalidDecl())
2279 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Douglas Gregor7caa6822009-07-24 20:34:43 +00002281 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002282 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002283 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002284 assert(Def->isStaticDataMember() && "Not a static data member?");
2285 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Douglas Gregor0d035142009-10-27 18:42:08 +00002287 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002288 // We did not find an out-of-line definition of this static data member,
2289 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002290 // instantiate this definition (or provide a specialization for it) in
2291 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002292 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002293 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002294 Diag(PointOfInstantiation,
2295 diag::err_explicit_instantiation_undefined_member)
2296 << 2 << Var->getDeclName() << Var->getDeclContext();
2297 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002298 } else if (Var->getTemplateSpecializationKind()
2299 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002300 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002301 std::make_pair(Var, PointOfInstantiation));
2302 }
2303
Douglas Gregor7caa6822009-07-24 20:34:43 +00002304 return;
2305 }
2306
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002307 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002308 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002309 return;
2310
2311 // C++0x [temp.explicit]p9:
2312 // Except for inline functions, other explicit instantiation declarations
2313 // have the effect of suppressing the implicit instantiation of the entity
2314 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002315 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002316 == TSK_ExplicitInstantiationDeclaration)
2317 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Douglas Gregor7caa6822009-07-24 20:34:43 +00002319 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2320 if (Inst)
2321 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002322
Douglas Gregor7caa6822009-07-24 20:34:43 +00002323 // If we're performing recursive template instantiation, create our own
2324 // queue of pending implicit instantiations that we will instantiate later,
2325 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002326 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002327 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002328 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Douglas Gregor7caa6822009-07-24 20:34:43 +00002330 // Enter the scope of this instantiation. We don't use
2331 // PushDeclContext because we don't have a scope.
2332 DeclContext *PreviousContext = CurContext;
2333 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002335 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002336 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002337 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002338 CurContext = PreviousContext;
2339
2340 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002341 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2342 assert(MSInfo && "Missing member specialization information?");
2343 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2344 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002345 DeclGroupRef DG(Var);
2346 Consumer.HandleTopLevelDecl(DG);
2347 }
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Douglas Gregor7caa6822009-07-24 20:34:43 +00002349 if (Recursive) {
2350 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002351 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002352 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor7caa6822009-07-24 20:34:43 +00002354 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002355 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002356 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002357}
Douglas Gregor815215d2009-05-27 05:35:12 +00002358
Anders Carlsson09025312009-08-29 05:16:22 +00002359void
2360Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2361 const CXXConstructorDecl *Tmpl,
2362 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Anders Carlsson09025312009-08-29 05:16:22 +00002364 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002365 bool AnyErrors = false;
2366
Anders Carlsson09025312009-08-29 05:16:22 +00002367 // Instantiate all the initializers.
2368 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002369 InitsEnd = Tmpl->init_end();
2370 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002371 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002372
Chandler Carruth030ef472010-09-03 21:54:20 +00002373 // Only instantiate written initializers, let Sema re-construct implicit
2374 // ones.
2375 if (!Init->isWritten())
2376 continue;
2377
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002378 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002379 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002381 SourceLocation EllipsisLoc;
2382
2383 if (Init->isPackExpansion()) {
2384 // This is a pack expansion. We should expand it now.
2385 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2386 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2387 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2388 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002389 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002390 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002391 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2392 BaseTL.getSourceRange(),
2393 Unexpanded.data(),
2394 Unexpanded.size(),
2395 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002396 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002397 NumExpansions)) {
2398 AnyErrors = true;
2399 New->setInvalidDecl();
2400 continue;
2401 }
2402 assert(ShouldExpand && "Partial instantiation of base initializer?");
2403
2404 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002405 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002406 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2407
2408 // Instantiate the initializer.
2409 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2410 LParenLoc, NewArgs, RParenLoc)) {
2411 AnyErrors = true;
2412 break;
2413 }
2414
2415 // Instantiate the base type.
2416 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2417 TemplateArgs,
2418 Init->getSourceLocation(),
2419 New->getDeclName());
2420 if (!BaseTInfo) {
2421 AnyErrors = true;
2422 break;
2423 }
2424
2425 // Build the initializer.
2426 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2427 BaseTInfo,
2428 (Expr **)NewArgs.data(),
2429 NewArgs.size(),
2430 Init->getLParenLoc(),
2431 Init->getRParenLoc(),
2432 New->getParent(),
2433 SourceLocation());
2434 if (NewInit.isInvalid()) {
2435 AnyErrors = true;
2436 break;
2437 }
2438
2439 NewInits.push_back(NewInit.get());
2440 NewArgs.clear();
2441 }
2442
2443 continue;
2444 }
2445
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002446 // Instantiate the initializer.
2447 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002448 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002449 AnyErrors = true;
2450 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002451 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002452
Anders Carlsson09025312009-08-29 05:16:22 +00002453 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002454 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002455 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002456 TemplateArgs,
2457 Init->getSourceLocation(),
2458 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002459 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002460 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002461 New->setInvalidDecl();
2462 continue;
2463 }
2464
John McCalla93c9342009-12-07 02:54:59 +00002465 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002466 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002467 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002468 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002469 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002470 New->getParent(),
2471 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002472 } else if (Init->isMemberInitializer()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002473 FieldDecl *Member = cast<FieldDecl>(FindInstantiatedDecl(
2474 Init->getMemberLocation(),
2475 Init->getMember(),
2476 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002477
2478 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002479 NewArgs.size(),
2480 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002481 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002482 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002483 } else if (Init->isIndirectMemberInitializer()) {
2484 IndirectFieldDecl *IndirectMember =
2485 cast<IndirectFieldDecl>(FindInstantiatedDecl(
2486 Init->getMemberLocation(),
2487 Init->getIndirectMember(), TemplateArgs));
2488
2489 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2490 NewArgs.size(),
2491 Init->getSourceLocation(),
2492 Init->getLParenLoc(),
2493 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002494 }
2495
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002496 if (NewInit.isInvalid()) {
2497 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002498 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002499 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002500 // FIXME: It would be nice if ASTOwningVector had a release function.
2501 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002502
Anders Carlsson09025312009-08-29 05:16:22 +00002503 NewInits.push_back((MemInitTy *)NewInit.get());
2504 }
2505 }
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Anders Carlsson09025312009-08-29 05:16:22 +00002507 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002508 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002509 /*FIXME: ColonLoc */
2510 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002511 NewInits.data(), NewInits.size(),
2512 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002513}
2514
John McCall52a575a2009-08-29 08:11:13 +00002515// TODO: this could be templated if the various decl types used the
2516// same method name.
2517static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2518 ClassTemplateDecl *Instance) {
2519 Pattern = Pattern->getCanonicalDecl();
2520
2521 do {
2522 Instance = Instance->getCanonicalDecl();
2523 if (Pattern == Instance) return true;
2524 Instance = Instance->getInstantiatedFromMemberTemplate();
2525 } while (Instance);
2526
2527 return false;
2528}
2529
Douglas Gregor0d696532009-09-28 06:34:35 +00002530static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2531 FunctionTemplateDecl *Instance) {
2532 Pattern = Pattern->getCanonicalDecl();
2533
2534 do {
2535 Instance = Instance->getCanonicalDecl();
2536 if (Pattern == Instance) return true;
2537 Instance = Instance->getInstantiatedFromMemberTemplate();
2538 } while (Instance);
2539
2540 return false;
2541}
2542
Douglas Gregored9c0f92009-10-29 00:04:11 +00002543static bool
2544isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2545 ClassTemplatePartialSpecializationDecl *Instance) {
2546 Pattern
2547 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2548 do {
2549 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2550 Instance->getCanonicalDecl());
2551 if (Pattern == Instance)
2552 return true;
2553 Instance = Instance->getInstantiatedFromMember();
2554 } while (Instance);
2555
2556 return false;
2557}
2558
John McCall52a575a2009-08-29 08:11:13 +00002559static bool isInstantiationOf(CXXRecordDecl *Pattern,
2560 CXXRecordDecl *Instance) {
2561 Pattern = Pattern->getCanonicalDecl();
2562
2563 do {
2564 Instance = Instance->getCanonicalDecl();
2565 if (Pattern == Instance) return true;
2566 Instance = Instance->getInstantiatedFromMemberClass();
2567 } while (Instance);
2568
2569 return false;
2570}
2571
2572static bool isInstantiationOf(FunctionDecl *Pattern,
2573 FunctionDecl *Instance) {
2574 Pattern = Pattern->getCanonicalDecl();
2575
2576 do {
2577 Instance = Instance->getCanonicalDecl();
2578 if (Pattern == Instance) return true;
2579 Instance = Instance->getInstantiatedFromMemberFunction();
2580 } while (Instance);
2581
2582 return false;
2583}
2584
2585static bool isInstantiationOf(EnumDecl *Pattern,
2586 EnumDecl *Instance) {
2587 Pattern = Pattern->getCanonicalDecl();
2588
2589 do {
2590 Instance = Instance->getCanonicalDecl();
2591 if (Pattern == Instance) return true;
2592 Instance = Instance->getInstantiatedFromMemberEnum();
2593 } while (Instance);
2594
2595 return false;
2596}
2597
John McCalled976492009-12-04 22:46:56 +00002598static bool isInstantiationOf(UsingShadowDecl *Pattern,
2599 UsingShadowDecl *Instance,
2600 ASTContext &C) {
2601 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2602}
2603
2604static bool isInstantiationOf(UsingDecl *Pattern,
2605 UsingDecl *Instance,
2606 ASTContext &C) {
2607 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2608}
2609
John McCall7ba107a2009-11-18 02:36:19 +00002610static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2611 UsingDecl *Instance,
2612 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002613 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002614}
2615
2616static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002617 UsingDecl *Instance,
2618 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002619 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002620}
2621
John McCall52a575a2009-08-29 08:11:13 +00002622static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2623 VarDecl *Instance) {
2624 assert(Instance->isStaticDataMember());
2625
2626 Pattern = Pattern->getCanonicalDecl();
2627
2628 do {
2629 Instance = Instance->getCanonicalDecl();
2630 if (Pattern == Instance) return true;
2631 Instance = Instance->getInstantiatedFromStaticDataMember();
2632 } while (Instance);
2633
2634 return false;
2635}
2636
John McCalled976492009-12-04 22:46:56 +00002637// Other is the prospective instantiation
2638// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002639static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002640 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002641 if (UnresolvedUsingTypenameDecl *UUD
2642 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2643 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2644 return isInstantiationOf(UUD, UD, Ctx);
2645 }
2646 }
2647
2648 if (UnresolvedUsingValueDecl *UUD
2649 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002650 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2651 return isInstantiationOf(UUD, UD, Ctx);
2652 }
2653 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002654
Anders Carlsson0d8df782009-08-29 19:37:28 +00002655 return false;
2656 }
Mike Stump1eb44332009-09-09 15:08:12 +00002657
John McCall52a575a2009-08-29 08:11:13 +00002658 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2659 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002660
John McCall52a575a2009-08-29 08:11:13 +00002661 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2662 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002663
John McCall52a575a2009-08-29 08:11:13 +00002664 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2665 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002666
Douglas Gregor7caa6822009-07-24 20:34:43 +00002667 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002668 if (Var->isStaticDataMember())
2669 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2670
2671 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2672 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002673
Douglas Gregor0d696532009-09-28 06:34:35 +00002674 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2675 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2676
Douglas Gregored9c0f92009-10-29 00:04:11 +00002677 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2678 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2679 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2680 PartialSpec);
2681
Anders Carlssond8b285f2009-09-01 04:26:58 +00002682 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2683 if (!Field->getDeclName()) {
2684 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002685 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002686 cast<FieldDecl>(D);
2687 }
2688 }
Mike Stump1eb44332009-09-09 15:08:12 +00002689
John McCalled976492009-12-04 22:46:56 +00002690 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2691 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2692
2693 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2694 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2695
Douglas Gregor815215d2009-05-27 05:35:12 +00002696 return D->getDeclName() && isa<NamedDecl>(Other) &&
2697 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2698}
2699
2700template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002701static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002702 NamedDecl *D,
2703 ForwardIterator first,
2704 ForwardIterator last) {
2705 for (; first != last; ++first)
2706 if (isInstantiationOf(Ctx, D, *first))
2707 return cast<NamedDecl>(*first);
2708
2709 return 0;
2710}
2711
John McCall02cace72009-08-28 07:59:38 +00002712/// \brief Finds the instantiation of the given declaration context
2713/// within the current instantiation.
2714///
2715/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002716DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002717 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002718 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002719 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002720 return cast_or_null<DeclContext>(ID);
2721 } else return DC;
2722}
2723
Douglas Gregored961e72009-05-27 17:54:46 +00002724/// \brief Find the instantiation of the given declaration within the
2725/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002726///
2727/// This routine is intended to be used when \p D is a declaration
2728/// referenced from within a template, that needs to mapped into the
2729/// corresponding declaration within an instantiation. For example,
2730/// given:
2731///
2732/// \code
2733/// template<typename T>
2734/// struct X {
2735/// enum Kind {
2736/// KnownValue = sizeof(T)
2737/// };
2738///
2739/// bool getKind() const { return KnownValue; }
2740/// };
2741///
2742/// template struct X<int>;
2743/// \endcode
2744///
2745/// In the instantiation of X<int>::getKind(), we need to map the
2746/// EnumConstantDecl for KnownValue (which refers to
2747/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002748/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2749/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002750NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002751 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002752 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002753 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002754 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002755 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002756 // D is a local of some kind. Look into the map of local
2757 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002758 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002759 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002760
Douglas Gregore95b4092009-09-16 18:34:49 +00002761 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2762 if (!Record->isDependentContext())
2763 return D;
2764
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002765 // If the RecordDecl is actually the injected-class-name or a
2766 // "templated" declaration for a class template, class template
2767 // partial specialization, or a member class of a class template,
2768 // substitute into the injected-class-name of the class template
2769 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002770 QualType T;
2771 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2772
2773 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002774 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002775 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2776 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002777 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002778
2779 // If we call SubstType with an InjectedClassNameType here we
2780 // can end up in an infinite loop.
2781 T = Context.getTypeDeclType(Record);
2782 assert(isa<InjectedClassNameType>(T) &&
2783 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002784 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002785 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002786
2787 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002788 // Substitute into the injected-class-name to get the type
2789 // corresponding to the instantiation we want, which may also be
2790 // the current instantiation (if we're in a template
2791 // definition). This substitution should never fail, since we
2792 // know we can instantiate the injected-class-name or we
2793 // wouldn't have gotten to the injected-class-name!
2794
2795 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2796 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002797 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2798 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2799
2800 if (!T->isDependentType()) {
2801 assert(T->isRecordType() && "Instantiation must produce a record type");
2802 return T->getAs<RecordType>()->getDecl();
2803 }
2804
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002805 // We are performing "partial" template instantiation to create
2806 // the member declarations for the members of a class template
2807 // specialization. Therefore, D is actually referring to something
2808 // in the current instantiation. Look through the current
2809 // context, which contains actual instantiations, to find the
2810 // instantiation of the "current instantiation" that D refers
2811 // to.
2812 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002813 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002814 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002815 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002816 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002817 if (isInstantiationOf(ClassTemplate,
2818 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002819 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002820
2821 if (!DC->isDependentContext())
2822 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002823 }
2824
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002825 // We're performing "instantiation" of a member of the current
2826 // instantiation while we are type-checking the
2827 // definition. Compute the declaration context and return that.
2828 assert(!SawNonDependentContext &&
2829 "No dependent context while instantiating record");
2830 DeclContext *DC = computeDeclContext(T);
2831 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002832 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002833 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002834 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002835
Douglas Gregore95b4092009-09-16 18:34:49 +00002836 // Fall through to deal with other dependent record types (e.g.,
2837 // anonymous unions in class templates).
2838 }
John McCall52a575a2009-08-29 08:11:13 +00002839
Douglas Gregore95b4092009-09-16 18:34:49 +00002840 if (!ParentDC->isDependentContext())
2841 return D;
2842
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002843 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002844 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002845 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Douglas Gregor815215d2009-05-27 05:35:12 +00002847 if (ParentDC != D->getDeclContext()) {
2848 // We performed some kind of instantiation in the parent context,
2849 // so now we need to look into the instantiated parent context to
2850 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002851
John McCall3cb0ebd2010-03-10 03:28:59 +00002852 // If our context used to be dependent, we may need to instantiate
2853 // it before performing lookup into that context.
2854 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002855 if (!Spec->isDependentContext()) {
2856 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002857 const RecordType *Tag = T->getAs<RecordType>();
2858 assert(Tag && "type of non-dependent record is not a RecordType");
2859 if (!Tag->isBeingDefined() &&
2860 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2861 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00002862
2863 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002864 }
2865 }
2866
Douglas Gregor815215d2009-05-27 05:35:12 +00002867 NamedDecl *Result = 0;
2868 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002869 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002870 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2871 } else {
2872 // Since we don't have a name for the entity we're looking for,
2873 // our only option is to walk through all of the declarations to
2874 // find that name. This will occur in a few cases:
2875 //
2876 // - anonymous struct/union within a template
2877 // - unnamed class/struct/union/enum within a template
2878 //
2879 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002880 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002881 ParentDC->decls_begin(),
2882 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002883 }
Mike Stump1eb44332009-09-09 15:08:12 +00002884
John McCall9f54ad42009-12-10 09:41:52 +00002885 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002886 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2887 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002888 && "Unable to find instantiation of declaration!");
2889
Douglas Gregor815215d2009-05-27 05:35:12 +00002890 D = Result;
2891 }
2892
Douglas Gregor815215d2009-05-27 05:35:12 +00002893 return D;
2894}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002895
Mike Stump1eb44332009-09-09 15:08:12 +00002896/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002897/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002898void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002899 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00002900 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002901 PendingImplicitInstantiation Inst;
2902
2903 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002904 Inst = PendingInstantiations.front();
2905 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00002906 } else {
2907 Inst = PendingLocalImplicitInstantiations.front();
2908 PendingLocalImplicitInstantiations.pop_front();
2909 }
Mike Stump1eb44332009-09-09 15:08:12 +00002910
Douglas Gregor7caa6822009-07-24 20:34:43 +00002911 // Instantiate function definitions
2912 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00002913 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
2914 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00002915 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
2916 TSK_ExplicitInstantiationDefinition;
2917 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
2918 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002919 continue;
2920 }
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Douglas Gregor7caa6822009-07-24 20:34:43 +00002922 // Instantiate static data member definitions.
2923 VarDecl *Var = cast<VarDecl>(Inst.first);
2924 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002925
Chandler Carruth291b4412010-02-13 10:17:50 +00002926 // Don't try to instantiate declarations if the most recent redeclaration
2927 // is invalid.
2928 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2929 continue;
2930
2931 // Check if the most recent declaration has changed the specialization kind
2932 // and removed the need for implicit instantiation.
2933 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2934 case TSK_Undeclared:
2935 assert(false && "Cannot instantitiate an undeclared specialization.");
2936 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00002937 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00002938 continue; // No longer need to instantiate this type.
2939 case TSK_ExplicitInstantiationDefinition:
2940 // We only need an instantiation if the pending instantiation *is* the
2941 // explicit instantiation.
2942 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00002943 case TSK_ImplicitInstantiation:
2944 break;
2945 }
2946
John McCallf312b1e2010-08-26 23:41:50 +00002947 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
2948 "instantiating static data member "
2949 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002950
Chandler Carruth58e390e2010-08-25 08:27:02 +00002951 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
2952 TSK_ExplicitInstantiationDefinition;
2953 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
2954 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002955 }
2956}
John McCall0c01d182010-03-24 05:22:00 +00002957
2958void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2959 const MultiLevelTemplateArgumentList &TemplateArgs) {
2960 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2961 E = Pattern->ddiag_end(); I != E; ++I) {
2962 DependentDiagnostic *DD = *I;
2963
2964 switch (DD->getKind()) {
2965 case DependentDiagnostic::Access:
2966 HandleDependentAccessCheck(*DD, TemplateArgs);
2967 break;
2968 }
2969 }
2970}