blob: c0150c07bbf1cd7f1b5b0eda6c194910f2b7545d [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 *
Chris Lattner57ad3782011-02-17 20:34:02 +0000104TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
105 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
106 D->getIdentifier());
107 Owner->addDecl(Inst);
108 return Inst;
109}
110
111Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000112TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
113 assert(false && "Namespaces cannot be instantiated");
114 return D;
115}
116
John McCall3dbd3d52010-02-16 06:53:13 +0000117Decl *
118TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
119 NamespaceAliasDecl *Inst
120 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
121 D->getNamespaceLoc(),
122 D->getAliasLoc(),
123 D->getNamespace()->getIdentifier(),
124 D->getQualifierRange(),
125 D->getQualifier(),
126 D->getTargetNameLoc(),
127 D->getNamespace());
128 Owner->addDecl(Inst);
129 return Inst;
130}
131
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000132Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
133 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000134 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000135 if (DI->getType()->isDependentType() ||
136 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000137 DI = SemaRef.SubstType(DI, TemplateArgs,
138 D->getLocation(), D->getDeclName());
139 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000140 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000141 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000143 } else {
144 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 }
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 // Create the new typedef
148 TypedefDecl *Typedef
149 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000150 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000151 if (Invalid)
152 Typedef->setInvalidDecl();
153
John McCallcde5a402011-02-01 08:20:08 +0000154 // If the old typedef was the name for linkage purposes of an anonymous
155 // tag decl, re-establish that relationship for the new typedef.
156 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
157 TagDecl *oldTag = oldTagType->getDecl();
158 if (oldTag->getTypedefForAnonDecl() == D) {
159 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
160 assert(!newTag->getIdentifier() && !newTag->getTypedefForAnonDecl());
161 newTag->setTypedefForAnonDecl(Typedef);
162 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000163 }
164
John McCall5126fd02009-12-30 00:31:22 +0000165 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000166 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
167 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000168 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
169 }
170
John McCall1d8d1cc2010-08-01 02:01:53 +0000171 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000172
John McCall46460a62010-01-20 21:53:11 +0000173 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000174 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000176 return Typedef;
177}
178
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000179/// \brief Instantiate an initializer, breaking it into separate
180/// initialization arguments.
181///
182/// \param S The semantic analysis object.
183///
184/// \param Init The initializer to instantiate.
185///
186/// \param TemplateArgs Template arguments to be substituted into the
187/// initializer.
188///
189/// \param NewArgs Will be filled in with the instantiation arguments.
190///
191/// \returns true if an error occurred, false otherwise
192static bool InstantiateInitializer(Sema &S, Expr *Init,
193 const MultiLevelTemplateArgumentList &TemplateArgs,
194 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000195 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000196 SourceLocation &RParenLoc) {
197 NewArgs.clear();
198 LParenLoc = SourceLocation();
199 RParenLoc = SourceLocation();
200
201 if (!Init)
202 return false;
203
John McCall4765fa02010-12-06 08:20:24 +0000204 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000205 Init = ExprTemp->getSubExpr();
206
207 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
208 Init = Binder->getSubExpr();
209
210 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
211 Init = ICE->getSubExprAsWritten();
212
213 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
214 LParenLoc = ParenList->getLParenLoc();
215 RParenLoc = ParenList->getRParenLoc();
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000216 return S.SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
217 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000218 }
219
220 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000221 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000222 if (S.SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
223 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000224 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000225
Douglas Gregor28329e52010-03-24 21:22:47 +0000226 // FIXME: Fake locations!
227 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000228 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000229 return false;
230 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000231 }
232
John McCall60d7b3a2010-08-24 06:29:42 +0000233 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000234 if (Result.isInvalid())
235 return true;
236
237 NewArgs.push_back(Result.takeAs<Expr>());
238 return false;
239}
240
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000241Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000242 // If this is the variable for an anonymous struct or union,
243 // instantiate the anonymous struct/union type first.
244 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
245 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
246 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
247 return 0;
248
John McCallce3ff2b2009-08-25 22:02:44 +0000249 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000250 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000251 TemplateArgs,
252 D->getTypeSpecStartLoc(),
253 D->getDeclName());
254 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000255 return 0;
256
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000257 if (DI->getType()->isFunctionType()) {
258 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
259 << D->isStaticDataMember() << DI->getType();
260 return 0;
261 }
262
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000263 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000264 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
265 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000266 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000267 D->getStorageClass(),
268 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000269 Var->setThreadSpecified(D->isThreadSpecified());
270 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000271
John McCallb6217662010-03-15 10:12:16 +0000272 // Substitute the nested name specifier, if any.
273 if (SubstQualifier(D, Var))
274 return 0;
275
Mike Stump1eb44332009-09-09 15:08:12 +0000276 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000277 // out-of-line, the instantiation will have the same lexical
278 // context (which will be a namespace scope) as the template.
279 if (D->isOutOfLine())
280 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000281
John McCall46460a62010-01-20 21:53:11 +0000282 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000283
284 if (!D->isStaticDataMember())
285 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000286
Mike Stump390b4cc2009-05-16 07:39:55 +0000287 // FIXME: In theory, we could have a previous declaration for variables that
288 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000289 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000290 // FIXME: having to fake up a LookupResult is dumb.
291 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000292 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000293 if (D->isStaticDataMember())
294 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000295 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Douglas Gregor7caa6822009-07-24 20:34:43 +0000297 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000298 if (!D->isStaticDataMember())
299 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000300 Owner->makeDeclVisibleInContext(Var);
301 } else {
302 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000303 if (Owner->isFunctionOrMethod())
304 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000305 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000306 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000307
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000308 // Link instantiations of static data members back to the template from
309 // which they were instantiated.
310 if (Var->isStaticDataMember())
311 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000312 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000313
Douglas Gregor60c93c92010-02-09 07:26:29 +0000314 if (Var->getAnyInitializer()) {
315 // We already have an initializer in the class.
316 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000317 if (Var->isStaticDataMember() && !D->isOutOfLine())
318 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
319 else
320 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
321
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000322 // Instantiate the initializer.
323 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000324 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000325 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000326 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000327 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000328 // Attach the initializer to the declaration, if we have one.
329 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000330 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000331 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000332 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000333 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000334 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000335 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000336 RParenLoc,
337 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000338 } else {
339 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000340 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000341 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000342 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000343 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000344 // FIXME: Not too happy about invalidating the declaration
345 // because of a bogus initializer.
346 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000347 }
348
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000349 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000350 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000351 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000352
Douglas Gregor5764f612010-05-08 23:05:03 +0000353 // Diagnose unused local variables.
354 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
355 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000356
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000357 return Var;
358}
359
Abramo Bagnara6206d532010-06-05 05:09:32 +0000360Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
361 AccessSpecDecl* AD
362 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
363 D->getAccessSpecifierLoc(), D->getColonLoc());
364 Owner->addHiddenDecl(AD);
365 return AD;
366}
367
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000368Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
369 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000370 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000371 if (DI->getType()->isDependentType() ||
372 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000373 DI = SemaRef.SubstType(DI, TemplateArgs,
374 D->getLocation(), D->getDeclName());
375 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000376 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000377 Invalid = true;
378 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000379 // C++ [temp.arg.type]p3:
380 // If a declaration acquires a function type through a type
381 // dependent on a template-parameter and this causes a
382 // declaration that does not use the syntactic form of a
383 // function declarator to have function type, the program is
384 // ill-formed.
385 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000386 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000387 Invalid = true;
388 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000389 } else {
390 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000391 }
392
393 Expr *BitWidth = D->getBitWidth();
394 if (Invalid)
395 BitWidth = 0;
396 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000397 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000398 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
John McCall60d7b3a2010-08-24 06:29:42 +0000400 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000401 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000402 if (InstantiatedBitWidth.isInvalid()) {
403 Invalid = true;
404 BitWidth = 0;
405 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000406 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000407 }
408
John McCall07fb6be2009-10-22 23:33:21 +0000409 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
410 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000411 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000412 D->getLocation(),
413 D->isMutable(),
414 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000415 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000416 D->getAccess(),
417 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000418 if (!Field) {
419 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000420 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000421 }
Mike Stump1eb44332009-09-09 15:08:12 +0000422
John McCall1d8d1cc2010-08-01 02:01:53 +0000423 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000424
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000425 if (Invalid)
426 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000428 if (!Field->getDeclName()) {
429 // Keep track of where this decl came from.
430 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000431 }
432 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
433 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000434 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000435 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000436 }
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000438 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000439 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000440 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441
442 return Field;
443}
444
Francois Pichet87c2e122010-11-21 06:08:52 +0000445Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
446 NamedDecl **NamedChain =
447 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
448
449 int i = 0;
450 for (IndirectFieldDecl::chain_iterator PI =
451 D->chain_begin(), PE = D->chain_end();
452 PI != PE; ++PI)
453 NamedChain[i++] = (SemaRef.FindInstantiatedDecl(D->getLocation(),
454 *PI, TemplateArgs));
455
Francois Pichet40e17752010-12-09 10:07:54 +0000456 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000457 IndirectFieldDecl* IndirectField
458 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000459 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000460 NamedChain, D->getChainingSize());
461
462
463 IndirectField->setImplicit(D->isImplicit());
464 IndirectField->setAccess(D->getAccess());
465 Owner->addDecl(IndirectField);
466 return IndirectField;
467}
468
John McCall02cace72009-08-28 07:59:38 +0000469Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000470 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000471 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000472 if (TypeSourceInfo *Ty = D->getFriendType()) {
473 TypeSourceInfo *InstTy =
474 SemaRef.SubstType(Ty, TemplateArgs,
475 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000476 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000477 return 0;
John McCall02cace72009-08-28 07:59:38 +0000478
Douglas Gregor06245bf2010-04-07 17:57:12 +0000479 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
480 if (!FD)
481 return 0;
482
483 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000484 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000485 Owner->addDecl(FD);
486 return FD;
487 }
488
489 NamedDecl *ND = D->getFriendDecl();
490 assert(ND && "friend decl must be a decl or a type!");
491
John McCallaf2094e2010-04-08 09:05:18 +0000492 // All of the Visit implementations for the various potential friend
493 // declarations have to be carefully written to work for friend
494 // objects, with the most important detail being that the target
495 // decl should almost certainly not be placed in Owner.
496 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000497 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
John McCall02cace72009-08-28 07:59:38 +0000499 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000500 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
501 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000502 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000503 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000504 Owner->addDecl(FD);
505 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000506}
507
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000508Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
509 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Douglas Gregorac7610d2009-06-22 20:57:11 +0000511 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000512 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
John McCall60d7b3a2010-08-24 06:29:42 +0000514 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000515 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000516 if (InstantiatedAssertExpr.isInvalid())
517 return 0;
518
John McCall60d7b3a2010-08-24 06:29:42 +0000519 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000520 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000521 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000522 InstantiatedAssertExpr.get(),
523 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000524}
525
526Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000527 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000528 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000529 D->getTagKeywordLoc(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000530 /*PrevDecl=*/0, D->isScoped(),
531 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000532 if (D->isFixed()) {
533 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
534 // If we have type source information for the underlying type, it means it
535 // has been explicitly set by the user. Perform substitution on it before
536 // moving on.
537 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
538 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
539 TemplateArgs,
540 UnderlyingLoc,
541 DeclarationName()));
542
543 if (!Enum->getIntegerTypeSourceInfo())
544 Enum->setIntegerType(SemaRef.Context.IntTy);
545 }
546 else {
547 assert(!D->getIntegerType()->isDependentType()
548 && "Dependent type without type source info");
549 Enum->setIntegerType(D->getIntegerType());
550 }
551 }
552
John McCall5b629aa2010-10-22 23:36:17 +0000553 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
554
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000555 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000556 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000557 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000558 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000559 Enum->startDefinition();
560
Douglas Gregor96084f12010-03-01 19:00:07 +0000561 if (D->getDeclContext()->isFunctionOrMethod())
562 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
563
John McCalld226f652010-08-21 09:40:31 +0000564 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000565
566 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000567 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
568 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000569 EC != ECEnd; ++EC) {
570 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000571 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000572 if (Expr *UninstValue = EC->getInitExpr()) {
573 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000574 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000575 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCallce3ff2b2009-08-25 22:02:44 +0000577 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000578 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000579
580 // Drop the initial value and continue.
581 bool isInvalid = false;
582 if (Value.isInvalid()) {
583 Value = SemaRef.Owned((Expr *)0);
584 isInvalid = true;
585 }
586
Mike Stump1eb44332009-09-09 15:08:12 +0000587 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000588 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
589 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000590 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000591
592 if (isInvalid) {
593 if (EnumConst)
594 EnumConst->setInvalidDecl();
595 Enum->setInvalidDecl();
596 }
597
598 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000599 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
600
John McCall3b85ecf2010-01-23 22:37:59 +0000601 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000602 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000603 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000604 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000605
606 if (D->getDeclContext()->isFunctionOrMethod()) {
607 // If the enumeration is within a function or method, record the enum
608 // constant as a local.
609 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
610 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000611 }
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000614 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000615 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000616 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000617 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000618 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000619 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000620
621 return Enum;
622}
623
Douglas Gregor6477b692009-03-25 15:04:13 +0000624Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
625 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
626 return 0;
627}
628
John McCalle29ba202009-08-20 01:44:21 +0000629Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000630 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
631
Douglas Gregor550d9b22009-10-31 17:21:17 +0000632 // Create a local instantiation scope for this class template, which
633 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000634 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000635 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000636 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000637 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000638 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000639
640 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000641
642 // Instantiate the qualifier. We have to do this first in case
643 // we're a friend declaration, because if we are then we need to put
644 // the new declaration in the appropriate context.
645 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
646 if (Qualifier) {
647 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
648 Pattern->getQualifierRange(),
649 TemplateArgs);
650 if (!Qualifier) return 0;
651 }
652
653 CXXRecordDecl *PrevDecl = 0;
654 ClassTemplateDecl *PrevClassTemplate = 0;
655
Nick Lewycky37574f52010-11-08 23:29:42 +0000656 if (!isFriend && Pattern->getPreviousDeclaration()) {
657 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
658 if (Found.first != Found.second) {
659 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
660 if (PrevClassTemplate)
661 PrevDecl = PrevClassTemplate->getTemplatedDecl();
662 }
663 }
664
John McCall93ba8572010-03-25 06:39:04 +0000665 // If this isn't a friend, then it's a member template, in which
666 // case we just want to build the instantiation in the
667 // specialization. If it is a friend, we want to build it in
668 // the appropriate context.
669 DeclContext *DC = Owner;
670 if (isFriend) {
671 if (Qualifier) {
672 CXXScopeSpec SS;
673 SS.setScopeRep(Qualifier);
674 SS.setRange(Pattern->getQualifierRange());
675 DC = SemaRef.computeDeclContext(SS);
676 if (!DC) return 0;
677 } else {
678 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
679 Pattern->getDeclContext(),
680 TemplateArgs);
681 }
682
683 // Look for a previous declaration of the template in the owning
684 // context.
685 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
686 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
687 SemaRef.LookupQualifiedName(R, DC);
688
689 if (R.isSingleResult()) {
690 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
691 if (PrevClassTemplate)
692 PrevDecl = PrevClassTemplate->getTemplatedDecl();
693 }
694
695 if (!PrevClassTemplate && Qualifier) {
696 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000697 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
698 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000699 return 0;
700 }
701
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000702 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000703 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000704 bool Complain = true;
705
706 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
707 // template for struct std::tr1::__detail::_Map_base, where the
708 // template parameters of the friend declaration don't match the
709 // template parameters of the original declaration. In this one
710 // case, we don't complain about the ill-formed friend
711 // declaration.
712 if (isFriend && Pattern->getIdentifier() &&
713 Pattern->getIdentifier()->isStr("_Map_base") &&
714 DC->isNamespace() &&
715 cast<NamespaceDecl>(DC)->getIdentifier() &&
716 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
717 DeclContext *DCParent = DC->getParent();
718 if (DCParent->isNamespace() &&
719 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
720 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
721 DeclContext *DCParent2 = DCParent->getParent();
722 if (DCParent2->isNamespace() &&
723 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
724 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
725 DCParent2->getParent()->isTranslationUnit())
726 Complain = false;
727 }
728 }
729
John McCall93ba8572010-03-25 06:39:04 +0000730 TemplateParameterList *PrevParams
731 = PrevClassTemplate->getTemplateParameters();
732
733 // Make sure the parameter lists match.
734 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000735 Complain,
736 Sema::TPL_TemplateMatch)) {
737 if (Complain)
738 return 0;
739
740 AdoptedPreviousTemplateParams = true;
741 InstParams = PrevParams;
742 }
John McCall93ba8572010-03-25 06:39:04 +0000743
744 // Do some additional validation, then merge default arguments
745 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000746 if (!AdoptedPreviousTemplateParams &&
747 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000748 Sema::TPC_ClassTemplate))
749 return 0;
750 }
751 }
752
John McCalle29ba202009-08-20 01:44:21 +0000753 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000754 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000755 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000756 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000757 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000758
John McCall93ba8572010-03-25 06:39:04 +0000759 if (Qualifier)
760 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000761
John McCalle29ba202009-08-20 01:44:21 +0000762 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000763 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
764 D->getIdentifier(), InstParams, RecordInst,
765 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000766 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000767
John McCall93ba8572010-03-25 06:39:04 +0000768 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000769 if (PrevClassTemplate)
770 Inst->setAccess(PrevClassTemplate->getAccess());
771 else
772 Inst->setAccess(D->getAccess());
773
John McCall93ba8572010-03-25 06:39:04 +0000774 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
775 // TODO: do we want to track the instantiation progeny of this
776 // friend target decl?
777 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000778 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000779 if (!PrevClassTemplate)
780 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000781 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000782
783 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000784 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000785 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000786
Douglas Gregor259571e2009-10-30 22:42:42 +0000787 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000788 if (isFriend) {
789 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000790 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000791 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000792
John McCalle29ba202009-08-20 01:44:21 +0000793 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000794
795 if (!PrevClassTemplate) {
796 // Queue up any out-of-line partial specializations of this member
797 // class template; the client will force their instantiation once
798 // the enclosing class has been instantiated.
799 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
800 D->getPartialSpecializations(PartialSpecs);
801 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
802 if (PartialSpecs[I]->isOutOfLine())
803 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
804 }
805
John McCalle29ba202009-08-20 01:44:21 +0000806 return Inst;
807}
808
Douglas Gregord60e1052009-08-27 16:57:43 +0000809Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000810TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
811 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000812 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
813
814 // Lookup the already-instantiated declaration in the instantiation
815 // of the class template and return that.
816 DeclContext::lookup_result Found
817 = Owner->lookup(ClassTemplate->getDeclName());
818 if (Found.first == Found.second)
819 return 0;
820
821 ClassTemplateDecl *InstClassTemplate
822 = dyn_cast<ClassTemplateDecl>(*Found.first);
823 if (!InstClassTemplate)
824 return 0;
825
Douglas Gregord65587f2010-11-10 19:44:59 +0000826 if (ClassTemplatePartialSpecializationDecl *Result
827 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
828 return Result;
829
830 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000831}
832
833Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000834TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000835 // Create a local instantiation scope for this function template, which
836 // will contain the instantiations of the template parameters and then get
837 // merged with the local instantiation scope for the function template
838 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000839 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000840
Douglas Gregord60e1052009-08-27 16:57:43 +0000841 TemplateParameterList *TempParams = D->getTemplateParameters();
842 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000843 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000844 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000845
Douglas Gregora735b202009-10-13 14:39:41 +0000846 FunctionDecl *Instantiated = 0;
847 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
848 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
849 InstParams));
850 else
851 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
852 D->getTemplatedDecl(),
853 InstParams));
854
855 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000856 return 0;
857
John McCall46460a62010-01-20 21:53:11 +0000858 Instantiated->setAccess(D->getAccess());
859
Mike Stump1eb44332009-09-09 15:08:12 +0000860 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000861 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000862 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000863 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000864 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000865 assert(InstTemplate &&
866 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000867
John McCallb1a56e72010-03-26 23:10:15 +0000868 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
869
John McCalle976ffe2009-12-14 23:19:40 +0000870 // Link the instantiation back to the pattern *unless* this is a
871 // non-definition friend declaration.
872 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000873 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000874 InstTemplate->setInstantiatedFromMemberTemplate(D);
875
John McCallb1a56e72010-03-26 23:10:15 +0000876 // Make declarations visible in the appropriate context.
877 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000878 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000879
Douglas Gregord60e1052009-08-27 16:57:43 +0000880 return InstTemplate;
881}
882
Douglas Gregord475b8d2009-03-25 21:17:03 +0000883Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
884 CXXRecordDecl *PrevDecl = 0;
885 if (D->isInjectedClassName())
886 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000887 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000888 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
889 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000890 TemplateArgs);
891 if (!Prev) return 0;
892 PrevDecl = cast<CXXRecordDecl>(Prev);
893 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000894
895 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000896 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000897 D->getLocation(), D->getIdentifier(),
898 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000899
900 // Substitute the nested name specifier, if any.
901 if (SubstQualifier(D, Record))
902 return 0;
903
Douglas Gregord475b8d2009-03-25 21:17:03 +0000904 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000905 // FIXME: Check against AS_none is an ugly hack to work around the issue that
906 // the tag decls introduced by friend class declarations don't have an access
907 // specifier. Remove once this area of the code gets sorted out.
908 if (D->getAccess() != AS_none)
909 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000910 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000911 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000912
John McCall02cace72009-08-28 07:59:38 +0000913 // If the original function was part of a friend declaration,
914 // inherit its namespace state.
915 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
916 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
917
Douglas Gregor9901c572010-05-21 00:31:19 +0000918 // Make sure that anonymous structs and unions are recorded.
919 if (D->isAnonymousStructOrUnion()) {
920 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000921 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000922 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
923 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000924
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000925 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000926 return Record;
927}
928
John McCall02cace72009-08-28 07:59:38 +0000929/// Normal class members are of more specific types and therefore
930/// don't make it here. This function serves two purposes:
931/// 1) instantiating function templates
932/// 2) substituting friend declarations
933/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000934Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000935 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000936 // Check whether there is already a function template specialization for
937 // this declaration.
938 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
939 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000940 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000941 std::pair<const TemplateArgument *, unsigned> Innermost
942 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000944 FunctionDecl *SpecFunc
945 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
946 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor127102b2009-06-29 20:59:39 +0000948 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000949 if (SpecFunc)
950 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000951 }
Mike Stump1eb44332009-09-09 15:08:12 +0000952
John McCallb0cb0222010-03-27 05:57:59 +0000953 bool isFriend;
954 if (FunctionTemplate)
955 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
956 else
957 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
958
Douglas Gregor79c22782010-01-16 20:21:20 +0000959 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000960 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000961 !(isa<Decl>(Owner) &&
962 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000963 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Douglas Gregore53060f2009-06-25 22:08:12 +0000965 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000966 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
967 TInfo = SubstFunctionType(D, Params);
968 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000969 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000970 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000971
John McCalld325daa2010-03-26 04:53:08 +0000972 NestedNameSpecifier *Qualifier = D->getQualifier();
973 if (Qualifier) {
974 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
975 D->getQualifierRange(),
976 TemplateArgs);
977 if (!Qualifier) return 0;
978 }
979
John McCall68b6b872010-02-06 01:50:47 +0000980 // If we're instantiating a local function declaration, put the result
981 // in the owner; otherwise we need to find the instantiated context.
982 DeclContext *DC;
983 if (D->getDeclContext()->isFunctionOrMethod())
984 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000985 else if (isFriend && Qualifier) {
986 CXXScopeSpec SS;
987 SS.setScopeRep(Qualifier);
988 SS.setRange(D->getQualifierRange());
989 DC = SemaRef.computeDeclContext(SS);
990 if (!DC) return 0;
991 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000992 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
993 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000994 }
John McCall68b6b872010-02-06 01:50:47 +0000995
John McCall02cace72009-08-28 07:59:38 +0000996 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000997 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000998 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000999 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001000 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001001
John McCalld325daa2010-03-26 04:53:08 +00001002 if (Qualifier)
1003 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001004
John McCallb1a56e72010-03-26 23:10:15 +00001005 DeclContext *LexicalDC = Owner;
1006 if (!isFriend && D->isOutOfLine()) {
1007 assert(D->getDeclContext()->isFileContext());
1008 LexicalDC = D->getDeclContext();
1009 }
1010
1011 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Douglas Gregore53060f2009-06-25 22:08:12 +00001013 // Attach the parameters
1014 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001015 if (Params[P])
1016 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001017 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001018
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001019 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001020 if (TemplateParams) {
1021 // Our resulting instantiation is actually a function template, since we
1022 // are substituting only the outer template parameters. For example, given
1023 //
1024 // template<typename T>
1025 // struct X {
1026 // template<typename U> friend void f(T, U);
1027 // };
1028 //
1029 // X<int> x;
1030 //
1031 // We are instantiating the friend function template "f" within X<int>,
1032 // which means substituting int for T, but leaving "f" as a friend function
1033 // template.
1034 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001035 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001036 Function->getLocation(),
1037 Function->getDeclName(),
1038 TemplateParams, Function);
1039 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001040
1041 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001042
1043 if (isFriend && D->isThisDeclarationADefinition()) {
1044 // TODO: should we remember this connection regardless of whether
1045 // the friend declaration provided a body?
1046 FunctionTemplate->setInstantiatedFromMemberTemplate(
1047 D->getDescribedFunctionTemplate());
1048 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001049 } else if (FunctionTemplate) {
1050 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001051 std::pair<const TemplateArgument *, unsigned> Innermost
1052 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001053 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001054 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001055 Innermost.first,
1056 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001057 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001058 } else if (isFriend && D->isThisDeclarationADefinition()) {
1059 // TODO: should we remember this connection regardless of whether
1060 // the friend declaration provided a body?
1061 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001062 }
Douglas Gregora735b202009-10-13 14:39:41 +00001063
Douglas Gregore53060f2009-06-25 22:08:12 +00001064 if (InitFunctionInstantiation(Function, D))
1065 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregore53060f2009-06-25 22:08:12 +00001067 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001068 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001069
John McCall68263142009-11-18 22:49:29 +00001070 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1071 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1072
John McCallaf2094e2010-04-08 09:05:18 +00001073 if (DependentFunctionTemplateSpecializationInfo *Info
1074 = D->getDependentSpecializationInfo()) {
1075 assert(isFriend && "non-friend has dependent specialization info?");
1076
1077 // This needs to be set now for future sanity.
1078 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1079
1080 // Instantiate the explicit template arguments.
1081 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1082 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001083 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1084 ExplicitArgs, TemplateArgs))
1085 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001086
1087 // Map the candidate templates to their instantiations.
1088 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1089 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1090 Info->getTemplate(I),
1091 TemplateArgs);
1092 if (!Temp) return 0;
1093
1094 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1095 }
1096
1097 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1098 &ExplicitArgs,
1099 Previous))
1100 Function->setInvalidDecl();
1101
1102 isExplicitSpecialization = true;
1103
1104 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001105 // Look only into the namespace where the friend would be declared to
1106 // find a previous declaration. This is the innermost enclosing namespace,
1107 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001108 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001109
Douglas Gregora735b202009-10-13 14:39:41 +00001110 // In C++, the previous declaration we find might be a tag type
1111 // (class or enum). In this case, the new declaration will hide the
1112 // tag type. Note that this does does not apply if we're declaring a
1113 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001114 if (Previous.isSingleTagDecl())
1115 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001116 }
1117
John McCall9f54ad42009-12-10 09:41:52 +00001118 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001119 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001120
John McCall76d32642010-04-24 01:30:58 +00001121 NamedDecl *PrincipalDecl = (TemplateParams
1122 ? cast<NamedDecl>(FunctionTemplate)
1123 : Function);
1124
Douglas Gregora735b202009-10-13 14:39:41 +00001125 // If the original function was part of a friend declaration,
1126 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001127 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001128 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001129 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001130 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001131 else
Douglas Gregora735b202009-10-13 14:39:41 +00001132 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001133
1134 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1135 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001136
Gabor Greif77535df2010-08-30 22:25:56 +00001137 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001138
Douglas Gregor238058c2010-05-18 05:45:02 +00001139 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1140 D->isThisDeclarationADefinition()) {
1141 // Check for a function body.
1142 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001143 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001144 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1145 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1146 << Function->getDeclName();
1147 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1148 Function->setInvalidDecl();
1149 }
1150 // Check for redefinitions due to other instantiations of this or
1151 // a similar friend function.
1152 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1153 REnd = Function->redecls_end();
1154 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001155 if (*R == Function)
1156 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001157 switch (R->getFriendObjectKind()) {
1158 case Decl::FOK_None:
1159 if (!queuedInstantiation && R->isUsed(false)) {
1160 if (MemberSpecializationInfo *MSInfo
1161 = Function->getMemberSpecializationInfo()) {
1162 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1163 SourceLocation Loc = R->getLocation(); // FIXME
1164 MSInfo->setPointOfInstantiation(Loc);
1165 SemaRef.PendingLocalImplicitInstantiations.push_back(
1166 std::make_pair(Function, Loc));
1167 queuedInstantiation = true;
1168 }
1169 }
1170 }
1171 break;
1172 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001173 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001174 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001175 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001176 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1177 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001178 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001179 Function->setInvalidDecl();
1180 break;
1181 }
1182 }
1183 }
1184 }
Douglas Gregora735b202009-10-13 14:39:41 +00001185 }
1186
John McCall76d32642010-04-24 01:30:58 +00001187 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1188 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1189 PrincipalDecl->setNonMemberOperator();
1190
Douglas Gregore53060f2009-06-25 22:08:12 +00001191 return Function;
1192}
1193
Douglas Gregord60e1052009-08-27 16:57:43 +00001194Decl *
1195TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1196 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001197 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1198 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001199 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001200 // We are creating a function template specialization from a function
1201 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001202 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001203 std::pair<const TemplateArgument *, unsigned> Innermost
1204 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001206 FunctionDecl *SpecFunc
1207 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1208 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Douglas Gregor6b906862009-08-21 00:16:32 +00001210 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001211 if (SpecFunc)
1212 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001213 }
1214
John McCallb0cb0222010-03-27 05:57:59 +00001215 bool isFriend;
1216 if (FunctionTemplate)
1217 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1218 else
1219 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1220
Douglas Gregor79c22782010-01-16 20:21:20 +00001221 bool MergeWithParentScope = (TemplateParams != 0) ||
1222 !(isa<Decl>(Owner) &&
1223 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001224 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001225
John McCall4eab39f2010-10-19 02:26:41 +00001226 // Instantiate enclosing template arguments for friends.
1227 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1228 unsigned NumTempParamLists = 0;
1229 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1230 TempParamLists.set_size(NumTempParamLists);
1231 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1232 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1233 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1234 if (!InstParams)
1235 return NULL;
1236 TempParamLists[I] = InstParams;
1237 }
1238 }
1239
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001240 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001241 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1242 TInfo = SubstFunctionType(D, Params);
1243 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001244 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001245 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001246
Abramo Bagnara723df242010-12-14 22:11:44 +00001247 // \brief If the type of this function, after ignoring parentheses,
1248 // is not *directly* a function type, then we're instantiating a function
1249 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001250 //
1251 // typedef int functype(int, int);
1252 // functype func;
1253 //
1254 // In this case, we'll just go instantiate the ParmVarDecls that we
1255 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001256 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001257 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001258 llvm::SmallVector<QualType, 4> ParamTypes;
1259 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1260 D->getNumParams(), TemplateArgs, ParamTypes,
1261 &Params))
1262 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001263 }
1264
John McCallb0cb0222010-03-27 05:57:59 +00001265 NestedNameSpecifier *Qualifier = D->getQualifier();
1266 if (Qualifier) {
1267 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1268 D->getQualifierRange(),
1269 TemplateArgs);
1270 if (!Qualifier) return 0;
1271 }
1272
1273 DeclContext *DC = Owner;
1274 if (isFriend) {
1275 if (Qualifier) {
1276 CXXScopeSpec SS;
1277 SS.setScopeRep(Qualifier);
1278 SS.setRange(D->getQualifierRange());
1279 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001280
1281 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1282 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001283 } else {
1284 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1285 D->getDeclContext(),
1286 TemplateArgs);
1287 }
1288 if (!DC) return 0;
1289 }
1290
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001291 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001292 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001293 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Abramo Bagnara25777432010-08-11 22:01:17 +00001295 DeclarationNameInfo NameInfo
1296 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001297 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001298 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001299 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001300 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001301 Constructor->isInlineSpecified(),
1302 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001303 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001304 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Craig Silversteinb41d8992010-10-21 00:44:50 +00001305 NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001306 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001307 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001308 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001309 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001310 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001311 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001312 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001313 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001314 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1315 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001316 D->isStatic(),
1317 D->getStorageClassAsWritten(),
1318 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001319 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001320
John McCallb0cb0222010-03-27 05:57:59 +00001321 if (Qualifier)
1322 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001323
Douglas Gregord60e1052009-08-27 16:57:43 +00001324 if (TemplateParams) {
1325 // Our resulting instantiation is actually a function template, since we
1326 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001327 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001328 // template<typename T>
1329 // struct X {
1330 // template<typename U> void f(T, U);
1331 // };
1332 //
1333 // X<int> x;
1334 //
1335 // We are instantiating the member template "f" within X<int>, which means
1336 // substituting int for T, but leaving "f" as a member function template.
1337 // Build the function template itself.
1338 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1339 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001340 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001341 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001342 if (isFriend) {
1343 FunctionTemplate->setLexicalDeclContext(Owner);
1344 FunctionTemplate->setObjectOfFriendDecl(true);
1345 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001346 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001347 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001348 } else if (FunctionTemplate) {
1349 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001350 std::pair<const TemplateArgument *, unsigned> Innermost
1351 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001352 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001353 TemplateArgumentList::CreateCopy(SemaRef.Context,
1354 Innermost.first,
1355 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001356 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001357 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001358 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001359 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001360 }
1361
Mike Stump1eb44332009-09-09 15:08:12 +00001362 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001363 // out-of-line, the instantiation will have the same lexical
1364 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001365 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001366 if (NumTempParamLists)
1367 Method->setTemplateParameterListsInfo(SemaRef.Context,
1368 NumTempParamLists,
1369 TempParamLists.data());
1370
John McCallb0cb0222010-03-27 05:57:59 +00001371 Method->setLexicalDeclContext(Owner);
1372 Method->setObjectOfFriendDecl(true);
1373 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001374 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Douglas Gregor5545e162009-03-24 00:38:23 +00001376 // Attach the parameters
1377 for (unsigned P = 0; P < Params.size(); ++P)
1378 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001379 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001380
1381 if (InitMethodInstantiation(Method, D))
1382 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001383
Abramo Bagnara25777432010-08-11 22:01:17 +00001384 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1385 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001386
John McCallb0cb0222010-03-27 05:57:59 +00001387 if (!FunctionTemplate || TemplateParams || isFriend) {
1388 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Douglas Gregordec06662009-08-21 18:42:58 +00001390 // In C++, the previous declaration we find might be a tag type
1391 // (class or enum). In this case, the new declaration will hide the
1392 // tag type. Note that this does does not apply if we're declaring a
1393 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001394 if (Previous.isSingleTagDecl())
1395 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001396 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001397
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001398 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001399 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001400
Douglas Gregor4ba31362009-12-01 17:24:26 +00001401 if (D->isPure())
1402 SemaRef.CheckPureMethod(Method, SourceRange());
1403
John McCall46460a62010-01-20 21:53:11 +00001404 Method->setAccess(D->getAccess());
1405
Anders Carlsson9eefa222011-01-20 06:52:44 +00001406 SemaRef.CheckOverrideControl(Method);
1407
John McCallb0cb0222010-03-27 05:57:59 +00001408 if (FunctionTemplate) {
1409 // If there's a function template, let our caller handle it.
1410 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1411 // Don't hide a (potentially) valid declaration with an invalid one.
1412 } else {
1413 NamedDecl *DeclToAdd = (TemplateParams
1414 ? cast<NamedDecl>(FunctionTemplate)
1415 : Method);
1416 if (isFriend)
1417 Record->makeDeclVisibleInContext(DeclToAdd);
1418 else
1419 Owner->addDecl(DeclToAdd);
1420 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001421
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001422 return Method;
1423}
1424
Douglas Gregor615c5d42009-03-24 16:43:20 +00001425Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001426 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001427}
1428
Douglas Gregor03b2b072009-03-24 00:15:49 +00001429Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001430 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001431}
1432
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001433Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001434 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001435}
1436
Douglas Gregor6477b692009-03-25 15:04:13 +00001437ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001438 return SemaRef.SubstParmVarDecl(D, TemplateArgs, llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001439}
1440
John McCalle29ba202009-08-20 01:44:21 +00001441Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1442 TemplateTypeParmDecl *D) {
1443 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001444 const Type* T = D->getTypeForDecl();
1445 assert(T->isTemplateTypeParmType());
1446 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCalle29ba202009-08-20 01:44:21 +00001448 TemplateTypeParmDecl *Inst =
1449 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001450 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001451 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001452 D->wasDeclaredWithTypename(),
1453 D->isParameterPack());
1454
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001455 if (D->hasDefaultArgument())
1456 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001457
Douglas Gregor550d9b22009-10-31 17:21:17 +00001458 // Introduce this template parameter's instantiation into the instantiation
1459 // scope.
1460 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1461
John McCalle29ba202009-08-20 01:44:21 +00001462 return Inst;
1463}
1464
Douglas Gregor33642df2009-10-23 23:25:44 +00001465Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1466 NonTypeTemplateParmDecl *D) {
1467 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001468 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1469 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1470 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1471 bool IsExpandedParameterPack = false;
1472 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001473 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001474 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001475
1476 if (D->isExpandedParameterPack()) {
1477 // The non-type template parameter pack is an already-expanded pack
1478 // expansion of types. Substitute into each of the expanded types.
1479 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1480 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1481 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1482 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1483 TemplateArgs,
1484 D->getLocation(),
1485 D->getDeclName());
1486 if (!NewDI)
1487 return 0;
1488
1489 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1490 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1491 D->getLocation());
1492 if (NewT.isNull())
1493 return 0;
1494 ExpandedParameterPackTypes.push_back(NewT);
1495 }
1496
1497 IsExpandedParameterPack = true;
1498 DI = D->getTypeSourceInfo();
1499 T = DI->getType();
1500 } else if (isa<PackExpansionTypeLoc>(TL)) {
1501 // The non-type template parameter pack's type is a pack expansion of types.
1502 // Determine whether we need to expand this parameter pack into separate
1503 // types.
1504 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1505 TypeLoc Pattern = Expansion.getPatternLoc();
1506 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1507 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1508
1509 // Determine whether the set of unexpanded parameter packs can and should
1510 // be expanded.
1511 bool Expand = true;
1512 bool RetainExpansion = false;
1513 llvm::Optional<unsigned> OrigNumExpansions
1514 = Expansion.getTypePtr()->getNumExpansions();
1515 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1516 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1517 Pattern.getSourceRange(),
1518 Unexpanded.data(),
1519 Unexpanded.size(),
1520 TemplateArgs,
1521 Expand, RetainExpansion,
1522 NumExpansions))
1523 return 0;
1524
1525 if (Expand) {
1526 for (unsigned I = 0; I != *NumExpansions; ++I) {
1527 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1528 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1529 D->getLocation(),
1530 D->getDeclName());
1531 if (!NewDI)
1532 return 0;
1533
1534 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1535 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1536 NewDI->getType(),
1537 D->getLocation());
1538 if (NewT.isNull())
1539 return 0;
1540 ExpandedParameterPackTypes.push_back(NewT);
1541 }
1542
1543 // Note that we have an expanded parameter pack. The "type" of this
1544 // expanded parameter pack is the original expansion type, but callers
1545 // will end up using the expanded parameter pack types for type-checking.
1546 IsExpandedParameterPack = true;
1547 DI = D->getTypeSourceInfo();
1548 T = DI->getType();
1549 } else {
1550 // We cannot fully expand the pack expansion now, so substitute into the
1551 // pattern and create a new pack expansion type.
1552 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1553 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1554 D->getLocation(),
1555 D->getDeclName());
1556 if (!NewPattern)
1557 return 0;
1558
1559 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1560 NumExpansions);
1561 if (!DI)
1562 return 0;
1563
1564 T = DI->getType();
1565 }
1566 } else {
1567 // Simple case: substitution into a parameter that is not a parameter pack.
1568 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1569 D->getLocation(), D->getDeclName());
1570 if (!DI)
1571 return 0;
1572
1573 // Check that this type is acceptable for a non-type template parameter.
1574 bool Invalid = false;
1575 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1576 D->getLocation());
1577 if (T.isNull()) {
1578 T = SemaRef.Context.IntTy;
1579 Invalid = true;
1580 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001581 }
1582
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001583 NonTypeTemplateParmDecl *Param;
1584 if (IsExpandedParameterPack)
1585 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1586 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001587 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001588 D->getPosition(),
1589 D->getIdentifier(), T,
1590 DI,
1591 ExpandedParameterPackTypes.data(),
1592 ExpandedParameterPackTypes.size(),
1593 ExpandedParameterPackTypesAsWritten.data());
1594 else
1595 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1596 D->getLocation(),
1597 D->getDepth() - TemplateArgs.getNumLevels(),
1598 D->getPosition(),
1599 D->getIdentifier(), T,
1600 D->isParameterPack(), DI);
1601
Douglas Gregor33642df2009-10-23 23:25:44 +00001602 if (Invalid)
1603 Param->setInvalidDecl();
1604
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001605 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001606
1607 // Introduce this template parameter's instantiation into the instantiation
1608 // scope.
1609 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001610 return Param;
1611}
1612
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001613Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001614TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1615 TemplateTemplateParmDecl *D) {
1616 // Instantiate the template parameter list of the template template parameter.
1617 TemplateParameterList *TempParams = D->getTemplateParameters();
1618 TemplateParameterList *InstParams;
1619 {
1620 // Perform the actual substitution of template parameters within a new,
1621 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001622 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001623 InstParams = SubstTemplateParams(TempParams);
1624 if (!InstParams)
1625 return NULL;
1626 }
1627
1628 // Build the template template parameter.
1629 TemplateTemplateParmDecl *Param
1630 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001631 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001632 D->getPosition(), D->isParameterPack(),
1633 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001634 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001635
Douglas Gregor9106ef72009-11-11 16:58:32 +00001636 // Introduce this template parameter's instantiation into the instantiation
1637 // scope.
1638 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1639
1640 return Param;
1641}
1642
Douglas Gregor48c32a72009-11-17 06:07:40 +00001643Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1644 // Using directives are never dependent, so they require no explicit
1645
1646 UsingDirectiveDecl *Inst
1647 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1648 D->getNamespaceKeyLocation(),
1649 D->getQualifierRange(), D->getQualifier(),
1650 D->getIdentLocation(),
1651 D->getNominatedNamespace(),
1652 D->getCommonAncestor());
1653 Owner->addDecl(Inst);
1654 return Inst;
1655}
1656
John McCalled976492009-12-04 22:46:56 +00001657Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001658
1659 // The nested name specifier may be dependent, for example
1660 // template <typename T> struct t {
1661 // struct s1 { T f1(); };
1662 // struct s2 : s1 { using s1::f1; };
1663 // };
1664 // template struct t<int>;
1665 // Here, in using s1::f1, s1 refers to t<T>::s1;
1666 // we need to substitute for t<int>::s1.
1667 NestedNameSpecifier *NNS =
1668 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1669 D->getNestedNameRange(),
1670 TemplateArgs);
1671 if (!NNS)
1672 return 0;
1673
1674 // The name info is non-dependent, so no transformation
1675 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001676 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001677
John McCall9f54ad42009-12-10 09:41:52 +00001678 // We only need to do redeclaration lookups if we're in a class
1679 // scope (in fact, it's not really even possible in non-class
1680 // scopes).
1681 bool CheckRedeclaration = Owner->isRecord();
1682
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001683 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1684 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001685
John McCalled976492009-12-04 22:46:56 +00001686 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001687 D->getNestedNameRange(),
1688 D->getUsingLocation(),
Douglas Gregor1b398202010-09-29 17:58:28 +00001689 NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001690 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001691 D->isTypeName());
1692
1693 CXXScopeSpec SS;
Douglas Gregor1b398202010-09-29 17:58:28 +00001694 SS.setScopeRep(NNS);
John McCalled976492009-12-04 22:46:56 +00001695 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001696
1697 if (CheckRedeclaration) {
1698 Prev.setHideTags(false);
1699 SemaRef.LookupQualifiedName(Prev, Owner);
1700
1701 // Check for invalid redeclarations.
1702 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1703 D->isTypeName(), SS,
1704 D->getLocation(), Prev))
1705 NewUD->setInvalidDecl();
1706
1707 }
1708
1709 if (!NewUD->isInvalidDecl() &&
1710 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001711 D->getLocation()))
1712 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001713
John McCalled976492009-12-04 22:46:56 +00001714 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1715 NewUD->setAccess(D->getAccess());
1716 Owner->addDecl(NewUD);
1717
John McCall9f54ad42009-12-10 09:41:52 +00001718 // Don't process the shadow decls for an invalid decl.
1719 if (NewUD->isInvalidDecl())
1720 return NewUD;
1721
John McCall323c3102009-12-22 22:26:37 +00001722 bool isFunctionScope = Owner->isFunctionOrMethod();
1723
John McCall9f54ad42009-12-10 09:41:52 +00001724 // Process the shadow decls.
1725 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1726 I != E; ++I) {
1727 UsingShadowDecl *Shadow = *I;
1728 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001729 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1730 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001731 TemplateArgs));
1732
1733 if (CheckRedeclaration &&
1734 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1735 continue;
1736
1737 UsingShadowDecl *InstShadow
1738 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1739 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001740
1741 if (isFunctionScope)
1742 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001743 }
John McCalled976492009-12-04 22:46:56 +00001744
1745 return NewUD;
1746}
1747
1748Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001749 // Ignore these; we handle them in bulk when processing the UsingDecl.
1750 return 0;
John McCalled976492009-12-04 22:46:56 +00001751}
1752
John McCall7ba107a2009-11-18 02:36:19 +00001753Decl * TemplateDeclInstantiator
1754 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001755 NestedNameSpecifier *NNS =
1756 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1757 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001758 TemplateArgs);
1759 if (!NNS)
1760 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001762 CXXScopeSpec SS;
1763 SS.setRange(D->getTargetNestedNameRange());
1764 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001766 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1767 // Hence, no tranformation is required for it.
1768 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001769 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001770 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001771 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001772 /*instantiation*/ true,
1773 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001774 if (UD)
John McCalled976492009-12-04 22:46:56 +00001775 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1776
John McCall7ba107a2009-11-18 02:36:19 +00001777 return UD;
1778}
1779
1780Decl * TemplateDeclInstantiator
1781 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1782 NestedNameSpecifier *NNS =
1783 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1784 D->getTargetNestedNameRange(),
1785 TemplateArgs);
1786 if (!NNS)
1787 return 0;
1788
1789 CXXScopeSpec SS;
1790 SS.setRange(D->getTargetNestedNameRange());
1791 SS.setScopeRep(NNS);
1792
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001793 DeclarationNameInfo NameInfo
1794 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1795
John McCall7ba107a2009-11-18 02:36:19 +00001796 NamedDecl *UD =
1797 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001798 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001799 /*instantiation*/ true,
1800 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001801 if (UD)
John McCalled976492009-12-04 22:46:56 +00001802 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1803
Anders Carlsson0d8df782009-08-29 19:37:28 +00001804 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001805}
1806
John McCallce3ff2b2009-08-25 22:02:44 +00001807Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001808 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001809 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001810 if (D->isInvalidDecl())
1811 return 0;
1812
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001813 return Instantiator.Visit(D);
1814}
1815
John McCalle29ba202009-08-20 01:44:21 +00001816/// \brief Instantiates a nested template parameter list in the current
1817/// instantiation context.
1818///
1819/// \param L The parameter list to instantiate
1820///
1821/// \returns NULL if there was an error
1822TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001823TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001824 // Get errors for all the parameters before bailing out.
1825 bool Invalid = false;
1826
1827 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001828 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001829 ParamVector Params;
1830 Params.reserve(N);
1831 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1832 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001833 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001834 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001835 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001836 }
1837
1838 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001839 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001840 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001841
1842 TemplateParameterList *InstL
1843 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1844 L->getLAngleLoc(), &Params.front(), N,
1845 L->getRAngleLoc());
1846 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001847}
John McCalle29ba202009-08-20 01:44:21 +00001848
Douglas Gregored9c0f92009-10-29 00:04:11 +00001849/// \brief Instantiate the declaration of a class template partial
1850/// specialization.
1851///
1852/// \param ClassTemplate the (instantiated) class template that is partially
1853// specialized by the instantiation of \p PartialSpec.
1854///
1855/// \param PartialSpec the (uninstantiated) class template partial
1856/// specialization that we are instantiating.
1857///
Douglas Gregord65587f2010-11-10 19:44:59 +00001858/// \returns The instantiated partial specialization, if successful; otherwise,
1859/// NULL to indicate an error.
1860ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001861TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1862 ClassTemplateDecl *ClassTemplate,
1863 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001864 // Create a local instantiation scope for this class template partial
1865 // specialization, which will contain the instantiations of the template
1866 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001867 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001868
Douglas Gregored9c0f92009-10-29 00:04:11 +00001869 // Substitute into the template parameters of the class template partial
1870 // specialization.
1871 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1872 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1873 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001874 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001875
1876 // Substitute into the template arguments of the class template partial
1877 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001878 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001879 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1880 PartialSpec->getNumTemplateArgsAsWritten(),
1881 InstTemplateArgs, TemplateArgs))
1882 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001883
Douglas Gregored9c0f92009-10-29 00:04:11 +00001884 // Check that the template argument list is well-formed for this
1885 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001886 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001887 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1888 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001889 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001890 false,
1891 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001892 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001893
1894 // Figure out where to insert this class template partial specialization
1895 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001896 void *InsertPos = 0;
1897 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001898 = ClassTemplate->findPartialSpecialization(Converted.data(),
1899 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001900
1901 // Build the canonical type that describes the converted template
1902 // arguments of the class template partial specialization.
1903 QualType CanonType
1904 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001905 Converted.data(),
1906 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001907
1908 // Build the fully-sugared type for this class template
1909 // specialization as the user wrote in the specialization
1910 // itself. This means that we'll pretty-print the type retrieved
1911 // from the specialization's declaration the way that the user
1912 // actually wrote the specialization, rather than formatting the
1913 // name based on the "canonical" representation used to store the
1914 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001915 TypeSourceInfo *WrittenTy
1916 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1917 TemplateName(ClassTemplate),
1918 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001919 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001920 CanonType);
1921
1922 if (PrevDecl) {
1923 // We've already seen a partial specialization with the same template
1924 // parameters and template arguments. This can happen, for example, when
1925 // substituting the outer template arguments ends up causing two
1926 // class template partial specializations of a member class template
1927 // to have identical forms, e.g.,
1928 //
1929 // template<typename T, typename U>
1930 // struct Outer {
1931 // template<typename X, typename Y> struct Inner;
1932 // template<typename Y> struct Inner<T, Y>;
1933 // template<typename Y> struct Inner<U, Y>;
1934 // };
1935 //
1936 // Outer<int, int> outer; // error: the partial specializations of Inner
1937 // // have the same signature.
1938 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001939 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001940 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1941 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001942 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001943 }
1944
1945
1946 // Create the class template partial specialization declaration.
1947 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001948 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1949 PartialSpec->getTagKind(),
1950 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001951 PartialSpec->getLocation(),
1952 InstParams,
1953 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001954 Converted.data(),
1955 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001956 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001957 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001958 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001959 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001960 // Substitute the nested name specifier, if any.
1961 if (SubstQualifier(PartialSpec, InstPartialSpec))
1962 return 0;
1963
Douglas Gregored9c0f92009-10-29 00:04:11 +00001964 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001965 InstPartialSpec->setTypeAsWritten(WrittenTy);
1966
Douglas Gregored9c0f92009-10-29 00:04:11 +00001967 // Add this partial specialization to the set of class template partial
1968 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001969 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001970 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001971}
1972
John McCall21ef0fa2010-03-11 09:03:00 +00001973TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001974TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001975 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001976 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1977 assert(OldTInfo && "substituting function without type source info");
1978 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001979 TypeSourceInfo *NewTInfo
1980 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1981 D->getTypeSpecStartLoc(),
1982 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001983 if (!NewTInfo)
1984 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001985
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001986 if (NewTInfo != OldTInfo) {
1987 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001988 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001989 if (FunctionProtoTypeLoc *OldProtoLoc
1990 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001991 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001992 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1993 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001994 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
1995 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
1996 OldIdx != NumOldParams; ++OldIdx) {
1997 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
1998 if (!OldParam->isParameterPack() ||
1999 (NewIdx < NumNewParams &&
2000 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2001 // Simple case: normal parameter, or a parameter pack that's
2002 // instantiated to a (still-dependent) parameter pack.
2003 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2004 Params.push_back(NewParam);
2005 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2006 NewParam);
2007 continue;
2008 }
2009
2010 // Parameter pack: make the instantiation an argument pack.
2011 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2012 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002013 unsigned NumArgumentsInExpansion
2014 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2015 TemplateArgs);
2016 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002017 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2018 Params.push_back(NewParam);
2019 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2020 NewParam);
2021 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002022 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002023 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002024 } else {
2025 // The function type itself was not dependent and therefore no
2026 // substitution occurred. However, we still need to instantiate
2027 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002028 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002029 if (FunctionProtoTypeLoc *OldProtoLoc
2030 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2031 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2032 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2033 if (!Parm)
2034 return 0;
2035 Params.push_back(Parm);
2036 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002037 }
2038 }
John McCall21ef0fa2010-03-11 09:03:00 +00002039 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002040}
2041
Mike Stump1eb44332009-09-09 15:08:12 +00002042/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002043/// declaration (New) from the corresponding fields of its template (Tmpl).
2044///
2045/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002046bool
2047TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002048 FunctionDecl *Tmpl) {
2049 if (Tmpl->isDeleted())
2050 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Douglas Gregorcca9e962009-07-01 22:01:06 +00002052 // If we are performing substituting explicitly-specified template arguments
2053 // or deduced template arguments into a function template and we reach this
2054 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002055 // to keeping the new function template specialization. We therefore
2056 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002057 // into a template instantiation for this specific function template
2058 // specialization, which is not a SFINAE context, so that we diagnose any
2059 // further errors in the declaration itself.
2060 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2061 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2062 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2063 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002064 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002065 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002066 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002067 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002068 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002069 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2070 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002071 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002072 }
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002075 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2076 assert(Proto && "Function template without prototype?");
2077
2078 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
2079 Proto->getNoReturnAttr()) {
2080 // The function has an exception specification or a "noreturn"
2081 // attribute. Substitute into each of the exception types.
2082 llvm::SmallVector<QualType, 4> Exceptions;
2083 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2084 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002085 if (const PackExpansionType *PackExpansion
2086 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2087 // We have a pack expansion. Instantiate it.
2088 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2089 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2090 Unexpanded);
2091 assert(!Unexpanded.empty() &&
2092 "Pack expansion without parameter packs?");
2093
2094 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002095 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002096 llvm::Optional<unsigned> NumExpansions
2097 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002098 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2099 SourceRange(),
2100 Unexpanded.data(),
2101 Unexpanded.size(),
2102 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002103 Expand,
2104 RetainExpansion,
2105 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002106 break;
2107
2108 if (!Expand) {
2109 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002110 // just substitute into the pattern and create a new pack expansion
2111 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002112 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2113 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2114 TemplateArgs,
2115 New->getLocation(), New->getDeclName());
2116 if (T.isNull())
2117 break;
2118
Douglas Gregorcded4f62011-01-14 17:04:44 +00002119 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002120 Exceptions.push_back(T);
2121 continue;
2122 }
2123
2124 // Substitute into the pack expansion pattern for each template
2125 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002126 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002127 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2128
2129 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2130 TemplateArgs,
2131 New->getLocation(), New->getDeclName());
2132 if (T.isNull()) {
2133 Invalid = true;
2134 break;
2135 }
2136
2137 Exceptions.push_back(T);
2138 }
2139
2140 if (Invalid)
2141 break;
2142
2143 continue;
2144 }
2145
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002146 QualType T
2147 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2148 New->getLocation(), New->getDeclName());
2149 if (T.isNull() ||
2150 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2151 continue;
2152
2153 Exceptions.push_back(T);
2154 }
2155
2156 // Rebuild the function type
2157
John McCalle23cf432010-12-14 08:05:40 +00002158 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2159 EPI.HasExceptionSpec = Proto->hasExceptionSpec();
2160 EPI.HasAnyExceptionSpec = Proto->hasAnyExceptionSpec();
2161 EPI.NumExceptions = Exceptions.size();
2162 EPI.Exceptions = Exceptions.data();
2163 EPI.ExtInfo = Proto->getExtInfo();
2164
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002165 const FunctionProtoType *NewProto
2166 = New->getType()->getAs<FunctionProtoType>();
2167 assert(NewProto && "Template instantiation without function prototype?");
2168 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2169 NewProto->arg_type_begin(),
2170 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002171 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002172 }
2173
John McCall1d8d1cc2010-08-01 02:01:53 +00002174 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002175
Douglas Gregore53060f2009-06-25 22:08:12 +00002176 return false;
2177}
2178
Douglas Gregor5545e162009-03-24 00:38:23 +00002179/// \brief Initializes common fields of an instantiated method
2180/// declaration (New) from the corresponding fields of its template
2181/// (Tmpl).
2182///
2183/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002184bool
2185TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002186 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002187 if (InitFunctionInstantiation(New, Tmpl))
2188 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Douglas Gregor5545e162009-03-24 00:38:23 +00002190 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002191 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002192 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002193
2194 // FIXME: attributes
2195 // FIXME: New needs a pointer to Tmpl
2196 return false;
2197}
Douglas Gregora58861f2009-05-13 20:28:22 +00002198
2199/// \brief Instantiate the definition of the given function from its
2200/// template.
2201///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002202/// \param PointOfInstantiation the point at which the instantiation was
2203/// required. Note that this is not precisely a "point of instantiation"
2204/// for the function, but it's close.
2205///
Douglas Gregora58861f2009-05-13 20:28:22 +00002206/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002207/// function template specialization or member function of a class template
2208/// specialization.
2209///
2210/// \param Recursive if true, recursively instantiates any functions that
2211/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002212///
2213/// \param DefinitionRequired if true, then we are performing an explicit
2214/// instantiation where the body of the function is required. Complain if
2215/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002216void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002217 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002218 bool Recursive,
2219 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002220 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002221 return;
2222
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002223 // Never instantiate an explicit specialization.
2224 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2225 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002226
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002227 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002228 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002229 Stmt *Pattern = 0;
2230 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002231 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002232
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002233 if (!Pattern) {
2234 if (DefinitionRequired) {
2235 if (Function->getPrimaryTemplate())
2236 Diag(PointOfInstantiation,
2237 diag::err_explicit_instantiation_undefined_func_template)
2238 << Function->getPrimaryTemplate();
2239 else
2240 Diag(PointOfInstantiation,
2241 diag::err_explicit_instantiation_undefined_member)
2242 << 1 << Function->getDeclName() << Function->getDeclContext();
2243
2244 if (PatternDecl)
2245 Diag(PatternDecl->getLocation(),
2246 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002247 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002248 } else if (Function->getTemplateSpecializationKind()
2249 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002250 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002251 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002252 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002253
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002254 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002255 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002256
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002257 // C++0x [temp.explicit]p9:
2258 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002259 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002260 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002261 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002262 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002263 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002264 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002266 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2267 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002268 return;
2269
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002270 // If we're performing recursive template instantiation, create our own
2271 // queue of pending implicit instantiations that we will instantiate later,
2272 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002273 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002274 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002275 if (Recursive) {
2276 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002277 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002278 }
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Douglas Gregor9679caf2010-05-12 17:27:19 +00002280 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002281 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002282 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002283
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002284 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002285 // recorded, unless we're actually a member function within a local
2286 // class, in which case we need to merge our results with the parent
2287 // scope (of the enclosing function).
2288 bool MergeWithParentScope = false;
2289 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2290 MergeWithParentScope = Rec->isLocalClass();
2291
2292 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002294 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002295 // instantiation scope, and set the parameter names to those used
2296 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002297 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002298 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2299 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002300 if (!PatternParam->isParameterPack()) {
2301 // Simple case: not a parameter pack.
2302 assert(FParamIdx < Function->getNumParams());
2303 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2304 FunctionParam->setDeclName(PatternParam->getDeclName());
2305 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2306 ++FParamIdx;
2307 continue;
2308 }
2309
2310 // Expand the parameter pack.
2311 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2312 for (unsigned NumFParams = Function->getNumParams();
2313 FParamIdx < NumFParams;
2314 ++FParamIdx) {
2315 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2316 FunctionParam->setDeclName(PatternParam->getDeclName());
2317 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2318 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002319 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002320
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002321 // Enter the scope of this instantiation. We don't use
2322 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002323 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002324
Mike Stump1eb44332009-09-09 15:08:12 +00002325 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002326 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002327
2328 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002329 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002330 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2331 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2332 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002333 }
2334
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002335 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002336 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002337
Douglas Gregor52604ab2009-09-11 21:19:12 +00002338 if (Body.isInvalid())
2339 Function->setInvalidDecl();
2340
John McCall9ae2f072010-08-23 23:25:46 +00002341 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002342 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002343
John McCall0c01d182010-03-24 05:22:00 +00002344 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2345
John McCalleee1d542011-02-14 07:13:47 +00002346 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002347
2348 DeclGroupRef DG(Function);
2349 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Douglas Gregor60406be2010-01-16 22:29:39 +00002351 // This class may have local implicit instantiations that need to be
2352 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002353 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002354 Scope.Exit();
2355
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002356 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002357 // Define any pending vtables.
2358 DefineUsedVTables();
2359
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002360 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002361 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002362 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002364 // Restore the set of pending vtables.
2365 VTableUses.swap(SavedVTableUses);
2366
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002367 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002368 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002369 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002370}
2371
2372/// \brief Instantiate the definition of the given variable from its
2373/// template.
2374///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002375/// \param PointOfInstantiation the point at which the instantiation was
2376/// required. Note that this is not precisely a "point of instantiation"
2377/// for the function, but it's close.
2378///
2379/// \param Var the already-instantiated declaration of a static member
2380/// variable of a class template specialization.
2381///
2382/// \param Recursive if true, recursively instantiates any functions that
2383/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002384///
2385/// \param DefinitionRequired if true, then we are performing an explicit
2386/// instantiation where an out-of-line definition of the member variable
2387/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002388void Sema::InstantiateStaticDataMemberDefinition(
2389 SourceLocation PointOfInstantiation,
2390 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002391 bool Recursive,
2392 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002393 if (Var->isInvalidDecl())
2394 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Douglas Gregor7caa6822009-07-24 20:34:43 +00002396 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002397 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002398 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002399 assert(Def->isStaticDataMember() && "Not a static data member?");
2400 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Douglas Gregor0d035142009-10-27 18:42:08 +00002402 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002403 // We did not find an out-of-line definition of this static data member,
2404 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002405 // instantiate this definition (or provide a specialization for it) in
2406 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002407 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002408 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002409 Diag(PointOfInstantiation,
2410 diag::err_explicit_instantiation_undefined_member)
2411 << 2 << Var->getDeclName() << Var->getDeclContext();
2412 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002413 } else if (Var->getTemplateSpecializationKind()
2414 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002415 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002416 std::make_pair(Var, PointOfInstantiation));
2417 }
2418
Douglas Gregor7caa6822009-07-24 20:34:43 +00002419 return;
2420 }
2421
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002422 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002423 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002424 return;
2425
2426 // C++0x [temp.explicit]p9:
2427 // Except for inline functions, other explicit instantiation declarations
2428 // have the effect of suppressing the implicit instantiation of the entity
2429 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002430 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002431 == TSK_ExplicitInstantiationDeclaration)
2432 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Douglas Gregor7caa6822009-07-24 20:34:43 +00002434 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2435 if (Inst)
2436 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Douglas Gregor7caa6822009-07-24 20:34:43 +00002438 // If we're performing recursive template instantiation, create our own
2439 // queue of pending implicit instantiations that we will instantiate later,
2440 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002441 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002442 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002443 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002444
Douglas Gregor7caa6822009-07-24 20:34:43 +00002445 // Enter the scope of this instantiation. We don't use
2446 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002447 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002449 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002450 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002451 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002452
2453 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002454
2455 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002456 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2457 assert(MSInfo && "Missing member specialization information?");
2458 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2459 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002460 DeclGroupRef DG(Var);
2461 Consumer.HandleTopLevelDecl(DG);
2462 }
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Douglas Gregor7caa6822009-07-24 20:34:43 +00002464 if (Recursive) {
2465 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002466 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002467 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Douglas Gregor7caa6822009-07-24 20:34:43 +00002469 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002470 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002471 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002472}
Douglas Gregor815215d2009-05-27 05:35:12 +00002473
Anders Carlsson09025312009-08-29 05:16:22 +00002474void
2475Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2476 const CXXConstructorDecl *Tmpl,
2477 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Anders Carlsson09025312009-08-29 05:16:22 +00002479 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002480 bool AnyErrors = false;
2481
Anders Carlsson09025312009-08-29 05:16:22 +00002482 // Instantiate all the initializers.
2483 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002484 InitsEnd = Tmpl->init_end();
2485 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002486 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002487
Chandler Carruth030ef472010-09-03 21:54:20 +00002488 // Only instantiate written initializers, let Sema re-construct implicit
2489 // ones.
2490 if (!Init->isWritten())
2491 continue;
2492
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002493 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002494 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002496 SourceLocation EllipsisLoc;
2497
2498 if (Init->isPackExpansion()) {
2499 // This is a pack expansion. We should expand it now.
2500 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2501 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2502 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2503 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002504 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002505 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002506 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2507 BaseTL.getSourceRange(),
2508 Unexpanded.data(),
2509 Unexpanded.size(),
2510 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002511 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002512 NumExpansions)) {
2513 AnyErrors = true;
2514 New->setInvalidDecl();
2515 continue;
2516 }
2517 assert(ShouldExpand && "Partial instantiation of base initializer?");
2518
2519 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002520 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002521 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2522
2523 // Instantiate the initializer.
2524 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2525 LParenLoc, NewArgs, RParenLoc)) {
2526 AnyErrors = true;
2527 break;
2528 }
2529
2530 // Instantiate the base type.
2531 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2532 TemplateArgs,
2533 Init->getSourceLocation(),
2534 New->getDeclName());
2535 if (!BaseTInfo) {
2536 AnyErrors = true;
2537 break;
2538 }
2539
2540 // Build the initializer.
2541 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2542 BaseTInfo,
2543 (Expr **)NewArgs.data(),
2544 NewArgs.size(),
2545 Init->getLParenLoc(),
2546 Init->getRParenLoc(),
2547 New->getParent(),
2548 SourceLocation());
2549 if (NewInit.isInvalid()) {
2550 AnyErrors = true;
2551 break;
2552 }
2553
2554 NewInits.push_back(NewInit.get());
2555 NewArgs.clear();
2556 }
2557
2558 continue;
2559 }
2560
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002561 // Instantiate the initializer.
2562 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002563 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002564 AnyErrors = true;
2565 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002566 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002567
Anders Carlsson09025312009-08-29 05:16:22 +00002568 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002569 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002570 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002571 TemplateArgs,
2572 Init->getSourceLocation(),
2573 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002574 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002575 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002576 New->setInvalidDecl();
2577 continue;
2578 }
2579
John McCalla93c9342009-12-07 02:54:59 +00002580 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002581 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002582 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002583 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002584 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002585 New->getParent(),
2586 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002587 } else if (Init->isMemberInitializer()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002588 FieldDecl *Member = cast<FieldDecl>(FindInstantiatedDecl(
2589 Init->getMemberLocation(),
2590 Init->getMember(),
2591 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002592
2593 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002594 NewArgs.size(),
2595 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002596 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002597 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002598 } else if (Init->isIndirectMemberInitializer()) {
2599 IndirectFieldDecl *IndirectMember =
2600 cast<IndirectFieldDecl>(FindInstantiatedDecl(
2601 Init->getMemberLocation(),
2602 Init->getIndirectMember(), TemplateArgs));
2603
2604 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2605 NewArgs.size(),
2606 Init->getSourceLocation(),
2607 Init->getLParenLoc(),
2608 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002609 }
2610
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002611 if (NewInit.isInvalid()) {
2612 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002613 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002614 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002615 // FIXME: It would be nice if ASTOwningVector had a release function.
2616 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Anders Carlsson09025312009-08-29 05:16:22 +00002618 NewInits.push_back((MemInitTy *)NewInit.get());
2619 }
2620 }
Mike Stump1eb44332009-09-09 15:08:12 +00002621
Anders Carlsson09025312009-08-29 05:16:22 +00002622 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002623 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002624 /*FIXME: ColonLoc */
2625 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002626 NewInits.data(), NewInits.size(),
2627 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002628}
2629
John McCall52a575a2009-08-29 08:11:13 +00002630// TODO: this could be templated if the various decl types used the
2631// same method name.
2632static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2633 ClassTemplateDecl *Instance) {
2634 Pattern = Pattern->getCanonicalDecl();
2635
2636 do {
2637 Instance = Instance->getCanonicalDecl();
2638 if (Pattern == Instance) return true;
2639 Instance = Instance->getInstantiatedFromMemberTemplate();
2640 } while (Instance);
2641
2642 return false;
2643}
2644
Douglas Gregor0d696532009-09-28 06:34:35 +00002645static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2646 FunctionTemplateDecl *Instance) {
2647 Pattern = Pattern->getCanonicalDecl();
2648
2649 do {
2650 Instance = Instance->getCanonicalDecl();
2651 if (Pattern == Instance) return true;
2652 Instance = Instance->getInstantiatedFromMemberTemplate();
2653 } while (Instance);
2654
2655 return false;
2656}
2657
Douglas Gregored9c0f92009-10-29 00:04:11 +00002658static bool
2659isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2660 ClassTemplatePartialSpecializationDecl *Instance) {
2661 Pattern
2662 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2663 do {
2664 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2665 Instance->getCanonicalDecl());
2666 if (Pattern == Instance)
2667 return true;
2668 Instance = Instance->getInstantiatedFromMember();
2669 } while (Instance);
2670
2671 return false;
2672}
2673
John McCall52a575a2009-08-29 08:11:13 +00002674static bool isInstantiationOf(CXXRecordDecl *Pattern,
2675 CXXRecordDecl *Instance) {
2676 Pattern = Pattern->getCanonicalDecl();
2677
2678 do {
2679 Instance = Instance->getCanonicalDecl();
2680 if (Pattern == Instance) return true;
2681 Instance = Instance->getInstantiatedFromMemberClass();
2682 } while (Instance);
2683
2684 return false;
2685}
2686
2687static bool isInstantiationOf(FunctionDecl *Pattern,
2688 FunctionDecl *Instance) {
2689 Pattern = Pattern->getCanonicalDecl();
2690
2691 do {
2692 Instance = Instance->getCanonicalDecl();
2693 if (Pattern == Instance) return true;
2694 Instance = Instance->getInstantiatedFromMemberFunction();
2695 } while (Instance);
2696
2697 return false;
2698}
2699
2700static bool isInstantiationOf(EnumDecl *Pattern,
2701 EnumDecl *Instance) {
2702 Pattern = Pattern->getCanonicalDecl();
2703
2704 do {
2705 Instance = Instance->getCanonicalDecl();
2706 if (Pattern == Instance) return true;
2707 Instance = Instance->getInstantiatedFromMemberEnum();
2708 } while (Instance);
2709
2710 return false;
2711}
2712
John McCalled976492009-12-04 22:46:56 +00002713static bool isInstantiationOf(UsingShadowDecl *Pattern,
2714 UsingShadowDecl *Instance,
2715 ASTContext &C) {
2716 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2717}
2718
2719static bool isInstantiationOf(UsingDecl *Pattern,
2720 UsingDecl *Instance,
2721 ASTContext &C) {
2722 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2723}
2724
John McCall7ba107a2009-11-18 02:36:19 +00002725static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2726 UsingDecl *Instance,
2727 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002728 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002729}
2730
2731static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002732 UsingDecl *Instance,
2733 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002734 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002735}
2736
John McCall52a575a2009-08-29 08:11:13 +00002737static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2738 VarDecl *Instance) {
2739 assert(Instance->isStaticDataMember());
2740
2741 Pattern = Pattern->getCanonicalDecl();
2742
2743 do {
2744 Instance = Instance->getCanonicalDecl();
2745 if (Pattern == Instance) return true;
2746 Instance = Instance->getInstantiatedFromStaticDataMember();
2747 } while (Instance);
2748
2749 return false;
2750}
2751
John McCalled976492009-12-04 22:46:56 +00002752// Other is the prospective instantiation
2753// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002754static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002755 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002756 if (UnresolvedUsingTypenameDecl *UUD
2757 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2758 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2759 return isInstantiationOf(UUD, UD, Ctx);
2760 }
2761 }
2762
2763 if (UnresolvedUsingValueDecl *UUD
2764 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002765 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2766 return isInstantiationOf(UUD, UD, Ctx);
2767 }
2768 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002769
Anders Carlsson0d8df782009-08-29 19:37:28 +00002770 return false;
2771 }
Mike Stump1eb44332009-09-09 15:08:12 +00002772
John McCall52a575a2009-08-29 08:11:13 +00002773 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2774 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002775
John McCall52a575a2009-08-29 08:11:13 +00002776 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2777 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002778
John McCall52a575a2009-08-29 08:11:13 +00002779 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2780 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002781
Douglas Gregor7caa6822009-07-24 20:34:43 +00002782 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002783 if (Var->isStaticDataMember())
2784 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2785
2786 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2787 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002788
Douglas Gregor0d696532009-09-28 06:34:35 +00002789 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2790 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2791
Douglas Gregored9c0f92009-10-29 00:04:11 +00002792 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2793 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2794 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2795 PartialSpec);
2796
Anders Carlssond8b285f2009-09-01 04:26:58 +00002797 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2798 if (!Field->getDeclName()) {
2799 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002800 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002801 cast<FieldDecl>(D);
2802 }
2803 }
Mike Stump1eb44332009-09-09 15:08:12 +00002804
John McCalled976492009-12-04 22:46:56 +00002805 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2806 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2807
2808 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2809 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2810
Douglas Gregor815215d2009-05-27 05:35:12 +00002811 return D->getDeclName() && isa<NamedDecl>(Other) &&
2812 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2813}
2814
2815template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002816static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002817 NamedDecl *D,
2818 ForwardIterator first,
2819 ForwardIterator last) {
2820 for (; first != last; ++first)
2821 if (isInstantiationOf(Ctx, D, *first))
2822 return cast<NamedDecl>(*first);
2823
2824 return 0;
2825}
2826
John McCall02cace72009-08-28 07:59:38 +00002827/// \brief Finds the instantiation of the given declaration context
2828/// within the current instantiation.
2829///
2830/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002831DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002832 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002833 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002834 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002835 return cast_or_null<DeclContext>(ID);
2836 } else return DC;
2837}
2838
Douglas Gregored961e72009-05-27 17:54:46 +00002839/// \brief Find the instantiation of the given declaration within the
2840/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002841///
2842/// This routine is intended to be used when \p D is a declaration
2843/// referenced from within a template, that needs to mapped into the
2844/// corresponding declaration within an instantiation. For example,
2845/// given:
2846///
2847/// \code
2848/// template<typename T>
2849/// struct X {
2850/// enum Kind {
2851/// KnownValue = sizeof(T)
2852/// };
2853///
2854/// bool getKind() const { return KnownValue; }
2855/// };
2856///
2857/// template struct X<int>;
2858/// \endcode
2859///
2860/// In the instantiation of X<int>::getKind(), we need to map the
2861/// EnumConstantDecl for KnownValue (which refers to
2862/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002863/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2864/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002865NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002866 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002867 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002868 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002869 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002870 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002871 // D is a local of some kind. Look into the map of local
2872 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002873 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2874 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2875 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002876
Chris Lattner57ad3782011-02-17 20:34:02 +00002877 if (Found) {
2878 if (Decl *FD = Found->dyn_cast<Decl *>())
2879 return cast<NamedDecl>(FD);
2880
2881 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2882 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2883 }
2884
2885 // If we didn't find the decl, then we must have a label decl that hasn't
2886 // been found yet. Lazily instantiate it and return it now.
2887 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002888
Chris Lattner57ad3782011-02-17 20:34:02 +00002889 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
2890 assert(Inst && "Failed to instantiate label??");
2891
2892 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2893 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002894 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002895
Douglas Gregore95b4092009-09-16 18:34:49 +00002896 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2897 if (!Record->isDependentContext())
2898 return D;
2899
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002900 // If the RecordDecl is actually the injected-class-name or a
2901 // "templated" declaration for a class template, class template
2902 // partial specialization, or a member class of a class template,
2903 // substitute into the injected-class-name of the class template
2904 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002905 QualType T;
2906 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2907
2908 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002909 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002910 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2911 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002912 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002913
2914 // If we call SubstType with an InjectedClassNameType here we
2915 // can end up in an infinite loop.
2916 T = Context.getTypeDeclType(Record);
2917 assert(isa<InjectedClassNameType>(T) &&
2918 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002919 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002920 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002921
2922 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002923 // Substitute into the injected-class-name to get the type
2924 // corresponding to the instantiation we want, which may also be
2925 // the current instantiation (if we're in a template
2926 // definition). This substitution should never fail, since we
2927 // know we can instantiate the injected-class-name or we
2928 // wouldn't have gotten to the injected-class-name!
2929
2930 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2931 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002932 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2933 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2934
2935 if (!T->isDependentType()) {
2936 assert(T->isRecordType() && "Instantiation must produce a record type");
2937 return T->getAs<RecordType>()->getDecl();
2938 }
2939
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002940 // We are performing "partial" template instantiation to create
2941 // the member declarations for the members of a class template
2942 // specialization. Therefore, D is actually referring to something
2943 // in the current instantiation. Look through the current
2944 // context, which contains actual instantiations, to find the
2945 // instantiation of the "current instantiation" that D refers
2946 // to.
2947 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002948 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002949 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002950 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002951 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002952 if (isInstantiationOf(ClassTemplate,
2953 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002954 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002955
2956 if (!DC->isDependentContext())
2957 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002958 }
2959
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002960 // We're performing "instantiation" of a member of the current
2961 // instantiation while we are type-checking the
2962 // definition. Compute the declaration context and return that.
2963 assert(!SawNonDependentContext &&
2964 "No dependent context while instantiating record");
2965 DeclContext *DC = computeDeclContext(T);
2966 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002967 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002968 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002969 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002970
Douglas Gregore95b4092009-09-16 18:34:49 +00002971 // Fall through to deal with other dependent record types (e.g.,
2972 // anonymous unions in class templates).
2973 }
John McCall52a575a2009-08-29 08:11:13 +00002974
Douglas Gregore95b4092009-09-16 18:34:49 +00002975 if (!ParentDC->isDependentContext())
2976 return D;
2977
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002978 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002979 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002980 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002981
Douglas Gregor815215d2009-05-27 05:35:12 +00002982 if (ParentDC != D->getDeclContext()) {
2983 // We performed some kind of instantiation in the parent context,
2984 // so now we need to look into the instantiated parent context to
2985 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002986
John McCall3cb0ebd2010-03-10 03:28:59 +00002987 // If our context used to be dependent, we may need to instantiate
2988 // it before performing lookup into that context.
2989 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002990 if (!Spec->isDependentContext()) {
2991 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002992 const RecordType *Tag = T->getAs<RecordType>();
2993 assert(Tag && "type of non-dependent record is not a RecordType");
2994 if (!Tag->isBeingDefined() &&
2995 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2996 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00002997
2998 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002999 }
3000 }
3001
Douglas Gregor815215d2009-05-27 05:35:12 +00003002 NamedDecl *Result = 0;
3003 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003004 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003005 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3006 } else {
3007 // Since we don't have a name for the entity we're looking for,
3008 // our only option is to walk through all of the declarations to
3009 // find that name. This will occur in a few cases:
3010 //
3011 // - anonymous struct/union within a template
3012 // - unnamed class/struct/union/enum within a template
3013 //
3014 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003015 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003016 ParentDC->decls_begin(),
3017 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003018 }
Mike Stump1eb44332009-09-09 15:08:12 +00003019
John McCall9f54ad42009-12-10 09:41:52 +00003020 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00003021 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
3022 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00003023 && "Unable to find instantiation of declaration!");
3024
Douglas Gregor815215d2009-05-27 05:35:12 +00003025 D = Result;
3026 }
3027
Douglas Gregor815215d2009-05-27 05:35:12 +00003028 return D;
3029}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003030
Mike Stump1eb44332009-09-09 15:08:12 +00003031/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003032/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003033void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003034 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003035 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003036 PendingImplicitInstantiation Inst;
3037
3038 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003039 Inst = PendingInstantiations.front();
3040 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003041 } else {
3042 Inst = PendingLocalImplicitInstantiations.front();
3043 PendingLocalImplicitInstantiations.pop_front();
3044 }
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Douglas Gregor7caa6822009-07-24 20:34:43 +00003046 // Instantiate function definitions
3047 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003048 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3049 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003050 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3051 TSK_ExplicitInstantiationDefinition;
3052 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3053 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003054 continue;
3055 }
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Douglas Gregor7caa6822009-07-24 20:34:43 +00003057 // Instantiate static data member definitions.
3058 VarDecl *Var = cast<VarDecl>(Inst.first);
3059 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003060
Chandler Carruth291b4412010-02-13 10:17:50 +00003061 // Don't try to instantiate declarations if the most recent redeclaration
3062 // is invalid.
3063 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3064 continue;
3065
3066 // Check if the most recent declaration has changed the specialization kind
3067 // and removed the need for implicit instantiation.
3068 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3069 case TSK_Undeclared:
3070 assert(false && "Cannot instantitiate an undeclared specialization.");
3071 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003072 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003073 continue; // No longer need to instantiate this type.
3074 case TSK_ExplicitInstantiationDefinition:
3075 // We only need an instantiation if the pending instantiation *is* the
3076 // explicit instantiation.
3077 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003078 case TSK_ImplicitInstantiation:
3079 break;
3080 }
3081
John McCallf312b1e2010-08-26 23:41:50 +00003082 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3083 "instantiating static data member "
3084 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Chandler Carruth58e390e2010-08-25 08:27:02 +00003086 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3087 TSK_ExplicitInstantiationDefinition;
3088 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3089 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003090 }
3091}
John McCall0c01d182010-03-24 05:22:00 +00003092
3093void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3094 const MultiLevelTemplateArgumentList &TemplateArgs) {
3095 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3096 E = Pattern->ddiag_end(); I != E; ++I) {
3097 DependentDiagnostic *DD = *I;
3098
3099 switch (DD->getKind()) {
3100 case DependentDiagnostic::Access:
3101 HandleDependentAccessCheck(*DD, TemplateArgs);
3102 break;
3103 }
3104 }
3105}