blob: 2ef688b0ebc9b74e8407a704cfb883845b251072 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallf312b1e2010-08-26 23:41:50 +000014#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000020#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000022#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025
26using namespace clang;
27
John McCallb6217662010-03-15 10:12:16 +000028bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
30 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
31 if (!OldQual) return false;
32
33 SourceRange QualRange = OldDecl->getQualifierRange();
34
35 NestedNameSpecifier *NewQual
36 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
37 if (!NewQual)
38 return true;
39
40 NewDecl->setQualifierInfo(NewQual, QualRange);
41 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
46 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
47 if (!OldQual) return false;
48
49 SourceRange QualRange = OldDecl->getQualifierRange();
50
51 NestedNameSpecifier *NewQual
52 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
53 if (!NewQual)
54 return true;
55
56 NewDecl->setQualifierInfo(NewQual, QualRange);
57 return false;
58}
59
Chandler Carruth4ced79f2010-06-25 03:22:07 +000060// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +000061void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
62 Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +000063 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
64 i != e; ++i) {
65 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +000066 // FIXME: This should be generalized to more than just the AlignedAttr.
67 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +000068 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +000069 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +000070 EnterExpressionEvaluationContext Unevaluated(*this,
John McCallf312b1e2010-08-26 23:41:50 +000071 Sema::Unevaluated);
Chandler Carruth4ced79f2010-06-25 03:22:07 +000072
Sean Huntcf807c42010-08-18 23:23:40 +000073 if (Aligned->isAlignmentExpr()) {
John McCall60d7b3a2010-08-24 06:29:42 +000074 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Nick Lewycky7663f392010-11-20 01:29:55 +000075 TemplateArgs);
Sean Huntcf807c42010-08-18 23:23:40 +000076 if (!Result.isInvalid())
77 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
78 }
79 else {
80 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
Nick Lewycky7663f392010-11-20 01:29:55 +000081 TemplateArgs,
82 Aligned->getLocation(),
83 DeclarationName());
Sean Huntcf807c42010-08-18 23:23:40 +000084 if (Result)
85 AddAlignedAttr(Aligned->getLocation(), New, Result);
86 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +000087 continue;
88 }
89 }
90
Anders Carlssond8fe2d52009-11-07 06:07:58 +000091 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +000092 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +000093 New->addAttr(NewAttr);
94 }
95}
96
Douglas Gregor4f722be2009-03-25 15:45:12 +000097Decl *
98TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
99 assert(false && "Translation units cannot be instantiated");
100 return D;
101}
102
103Decl *
104TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
105 assert(false && "Namespaces cannot be instantiated");
106 return D;
107}
108
John McCall3dbd3d52010-02-16 06:53:13 +0000109Decl *
110TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
111 NamespaceAliasDecl *Inst
112 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
113 D->getNamespaceLoc(),
114 D->getAliasLoc(),
115 D->getNamespace()->getIdentifier(),
116 D->getQualifierRange(),
117 D->getQualifier(),
118 D->getTargetNameLoc(),
119 D->getNamespace());
120 Owner->addDecl(Inst);
121 return Inst;
122}
123
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000124Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
125 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000126 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000127 if (DI->getType()->isDependentType() ||
128 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000129 DI = SemaRef.SubstType(DI, TemplateArgs,
130 D->getLocation(), D->getDeclName());
131 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000132 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000133 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000134 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000135 } else {
136 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000137 }
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000139 // Create the new typedef
140 TypedefDecl *Typedef
141 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000142 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000143 if (Invalid)
144 Typedef->setInvalidDecl();
145
Douglas Gregord57a38e2010-04-23 16:25:07 +0000146 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
147 TagDecl *TD = TT->getDecl();
148
149 // If the TagDecl that the TypedefDecl points to is an anonymous decl
150 // keep track of the TypedefDecl.
151 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
152 TD->setTypedefForAnonDecl(Typedef);
153 }
154
John McCall5126fd02009-12-30 00:31:22 +0000155 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000156 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
157 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000158 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
159 }
160
John McCall1d8d1cc2010-08-01 02:01:53 +0000161 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000162
John McCall46460a62010-01-20 21:53:11 +0000163 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000164 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000166 return Typedef;
167}
168
Douglas Gregor6eef5192009-12-14 19:27:10 +0000169/// \brief Instantiate the arguments provided as part of initialization.
170///
171/// \returns true if an error occurred, false otherwise.
172static bool InstantiateInitializationArguments(Sema &SemaRef,
173 Expr **Args, unsigned NumArgs,
174 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallca0408f2010-08-23 06:44:23 +0000175 ASTOwningVector<Expr*> &InitArgs) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000176 for (unsigned I = 0; I != NumArgs; ++I) {
177 // When we hit the first defaulted argument, break out of the loop:
178 // we don't pass those default arguments on.
179 if (Args[I]->isDefaultArgument())
180 break;
181
John McCall60d7b3a2010-08-24 06:29:42 +0000182 ExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000183 if (Arg.isInvalid())
184 return true;
185
Douglas Gregor6eef5192009-12-14 19:27:10 +0000186 InitArgs.push_back(Arg.release());
Douglas Gregor6eef5192009-12-14 19:27:10 +0000187 }
188
189 return false;
190}
191
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000192/// \brief Instantiate an initializer, breaking it into separate
193/// initialization arguments.
194///
195/// \param S The semantic analysis object.
196///
197/// \param Init The initializer to instantiate.
198///
199/// \param TemplateArgs Template arguments to be substituted into the
200/// initializer.
201///
202/// \param NewArgs Will be filled in with the instantiation arguments.
203///
204/// \returns true if an error occurred, false otherwise
205static bool InstantiateInitializer(Sema &S, Expr *Init,
206 const MultiLevelTemplateArgumentList &TemplateArgs,
207 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000208 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000209 SourceLocation &RParenLoc) {
210 NewArgs.clear();
211 LParenLoc = SourceLocation();
212 RParenLoc = SourceLocation();
213
214 if (!Init)
215 return false;
216
John McCall4765fa02010-12-06 08:20:24 +0000217 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000218 Init = ExprTemp->getSubExpr();
219
220 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
221 Init = Binder->getSubExpr();
222
223 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
224 Init = ICE->getSubExprAsWritten();
225
226 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
227 LParenLoc = ParenList->getLParenLoc();
228 RParenLoc = ParenList->getRParenLoc();
229 return InstantiateInitializationArguments(S, ParenList->getExprs(),
230 ParenList->getNumExprs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000231 TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000232 }
233
234 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000235 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
236 if (InstantiateInitializationArguments(S,
237 Construct->getArgs(),
238 Construct->getNumArgs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000239 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000240 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000241
Douglas Gregor28329e52010-03-24 21:22:47 +0000242 // FIXME: Fake locations!
243 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000244 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000245 return false;
246 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000247 }
248
John McCall60d7b3a2010-08-24 06:29:42 +0000249 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000250 if (Result.isInvalid())
251 return true;
252
253 NewArgs.push_back(Result.takeAs<Expr>());
254 return false;
255}
256
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000257Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000258 // If this is the variable for an anonymous struct or union,
259 // instantiate the anonymous struct/union type first.
260 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
261 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
262 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
263 return 0;
264
John McCallce3ff2b2009-08-25 22:02:44 +0000265 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000266 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000267 TemplateArgs,
268 D->getTypeSpecStartLoc(),
269 D->getDeclName());
270 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000271 return 0;
272
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000273 if (DI->getType()->isFunctionType()) {
274 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
275 << D->isStaticDataMember() << DI->getType();
276 return 0;
277 }
278
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000279 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000280 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
281 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000282 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000283 D->getStorageClass(),
284 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000285 Var->setThreadSpecified(D->isThreadSpecified());
286 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000287
John McCallb6217662010-03-15 10:12:16 +0000288 // Substitute the nested name specifier, if any.
289 if (SubstQualifier(D, Var))
290 return 0;
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000293 // out-of-line, the instantiation will have the same lexical
294 // context (which will be a namespace scope) as the template.
295 if (D->isOutOfLine())
296 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000297
John McCall46460a62010-01-20 21:53:11 +0000298 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000299
300 if (!D->isStaticDataMember())
301 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000302
Mike Stump390b4cc2009-05-16 07:39:55 +0000303 // FIXME: In theory, we could have a previous declaration for variables that
304 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000305 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000306 // FIXME: having to fake up a LookupResult is dumb.
307 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000308 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000309 if (D->isStaticDataMember())
310 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000311 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregor7caa6822009-07-24 20:34:43 +0000313 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000314 if (!D->isStaticDataMember())
315 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000316 Owner->makeDeclVisibleInContext(Var);
317 } else {
318 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000319 if (Owner->isFunctionOrMethod())
320 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000321 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000322 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000323
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000324 // Link instantiations of static data members back to the template from
325 // which they were instantiated.
326 if (Var->isStaticDataMember())
327 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000328 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000329
Douglas Gregor60c93c92010-02-09 07:26:29 +0000330 if (Var->getAnyInitializer()) {
331 // We already have an initializer in the class.
332 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000333 if (Var->isStaticDataMember() && !D->isOutOfLine())
334 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
335 else
336 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
337
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000338 // Instantiate the initializer.
339 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000340 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000341 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000342 InitArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000343 // Attach the initializer to the declaration.
344 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000345 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000346 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000347 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000348 move_arg(InitArgs),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000349 RParenLoc);
350 } else if (InitArgs.size() == 1) {
John McCall9ae2f072010-08-23 23:25:46 +0000351 Expr *Init = InitArgs.take()[0];
352 SemaRef.AddInitializerToDecl(Var, Init, false);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000353 } else {
354 assert(InitArgs.size() == 0);
John McCalld226f652010-08-21 09:40:31 +0000355 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000356 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000357 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000358 // FIXME: Not too happy about invalidating the declaration
359 // because of a bogus initializer.
360 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000361 }
362
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000363 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000364 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000365 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000366
Douglas Gregor5764f612010-05-08 23:05:03 +0000367 // Diagnose unused local variables.
368 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
369 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000370
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000371 return Var;
372}
373
Abramo Bagnara6206d532010-06-05 05:09:32 +0000374Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
375 AccessSpecDecl* AD
376 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
377 D->getAccessSpecifierLoc(), D->getColonLoc());
378 Owner->addHiddenDecl(AD);
379 return AD;
380}
381
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000382Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
383 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000384 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000385 if (DI->getType()->isDependentType() ||
386 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000387 DI = SemaRef.SubstType(DI, TemplateArgs,
388 D->getLocation(), D->getDeclName());
389 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000390 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000391 Invalid = true;
392 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000393 // C++ [temp.arg.type]p3:
394 // If a declaration acquires a function type through a type
395 // dependent on a template-parameter and this causes a
396 // declaration that does not use the syntactic form of a
397 // function declarator to have function type, the program is
398 // ill-formed.
399 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000400 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000401 Invalid = true;
402 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000403 } else {
404 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000405 }
406
407 Expr *BitWidth = D->getBitWidth();
408 if (Invalid)
409 BitWidth = 0;
410 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000411 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000412 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
John McCall60d7b3a2010-08-24 06:29:42 +0000414 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000415 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000416 if (InstantiatedBitWidth.isInvalid()) {
417 Invalid = true;
418 BitWidth = 0;
419 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000420 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000421 }
422
John McCall07fb6be2009-10-22 23:33:21 +0000423 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
424 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000425 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000426 D->getLocation(),
427 D->isMutable(),
428 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000429 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 D->getAccess(),
431 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000432 if (!Field) {
433 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000434 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436
John McCall1d8d1cc2010-08-01 02:01:53 +0000437 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000438
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000439 if (Invalid)
440 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000442 if (!Field->getDeclName()) {
443 // Keep track of where this decl came from.
444 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000445 }
446 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
447 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000448 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000449 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000452 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000453 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000454 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455
456 return Field;
457}
458
Francois Pichet87c2e122010-11-21 06:08:52 +0000459Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
460 NamedDecl **NamedChain =
461 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
462
463 int i = 0;
464 for (IndirectFieldDecl::chain_iterator PI =
465 D->chain_begin(), PE = D->chain_end();
466 PI != PE; ++PI)
467 NamedChain[i++] = (SemaRef.FindInstantiatedDecl(D->getLocation(),
468 *PI, TemplateArgs));
469
Francois Pichet40e17752010-12-09 10:07:54 +0000470 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000471 IndirectFieldDecl* IndirectField
472 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000473 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000474 NamedChain, D->getChainingSize());
475
476
477 IndirectField->setImplicit(D->isImplicit());
478 IndirectField->setAccess(D->getAccess());
479 Owner->addDecl(IndirectField);
480 return IndirectField;
481}
482
John McCall02cace72009-08-28 07:59:38 +0000483Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000484 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000485 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000486 if (TypeSourceInfo *Ty = D->getFriendType()) {
487 TypeSourceInfo *InstTy =
488 SemaRef.SubstType(Ty, TemplateArgs,
489 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000490 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000491 return 0;
John McCall02cace72009-08-28 07:59:38 +0000492
Douglas Gregor06245bf2010-04-07 17:57:12 +0000493 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
494 if (!FD)
495 return 0;
496
497 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000498 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 Owner->addDecl(FD);
500 return FD;
501 }
502
503 NamedDecl *ND = D->getFriendDecl();
504 assert(ND && "friend decl must be a decl or a type!");
505
John McCallaf2094e2010-04-08 09:05:18 +0000506 // All of the Visit implementations for the various potential friend
507 // declarations have to be carefully written to work for friend
508 // objects, with the most important detail being that the target
509 // decl should almost certainly not be placed in Owner.
510 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000511 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
John McCall02cace72009-08-28 07:59:38 +0000513 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000514 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
515 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000516 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000517 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000518 Owner->addDecl(FD);
519 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000520}
521
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000522Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
523 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregorac7610d2009-06-22 20:57:11 +0000525 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000526 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000527
John McCall60d7b3a2010-08-24 06:29:42 +0000528 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000529 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000530 if (InstantiatedAssertExpr.isInvalid())
531 return 0;
532
John McCall60d7b3a2010-08-24 06:29:42 +0000533 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000534 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000535 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000536 InstantiatedAssertExpr.get(),
537 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000538}
539
540Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000541 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000542 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000543 D->getTagKeywordLoc(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000544 /*PrevDecl=*/0, D->isScoped(),
545 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000546 if (D->isFixed()) {
547 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
548 // If we have type source information for the underlying type, it means it
549 // has been explicitly set by the user. Perform substitution on it before
550 // moving on.
551 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
552 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
553 TemplateArgs,
554 UnderlyingLoc,
555 DeclarationName()));
556
557 if (!Enum->getIntegerTypeSourceInfo())
558 Enum->setIntegerType(SemaRef.Context.IntTy);
559 }
560 else {
561 assert(!D->getIntegerType()->isDependentType()
562 && "Dependent type without type source info");
563 Enum->setIntegerType(D->getIntegerType());
564 }
565 }
566
John McCall5b629aa2010-10-22 23:36:17 +0000567 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
568
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000569 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000570 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000571 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000572 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000573 Enum->startDefinition();
574
Douglas Gregor96084f12010-03-01 19:00:07 +0000575 if (D->getDeclContext()->isFunctionOrMethod())
576 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
577
John McCalld226f652010-08-21 09:40:31 +0000578 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000579
580 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000581 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
582 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000583 EC != ECEnd; ++EC) {
584 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000585 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000586 if (Expr *UninstValue = EC->getInitExpr()) {
587 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000588 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000589 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000590
John McCallce3ff2b2009-08-25 22:02:44 +0000591 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000592 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000593
594 // Drop the initial value and continue.
595 bool isInvalid = false;
596 if (Value.isInvalid()) {
597 Value = SemaRef.Owned((Expr *)0);
598 isInvalid = true;
599 }
600
Mike Stump1eb44332009-09-09 15:08:12 +0000601 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000602 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
603 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000604 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605
606 if (isInvalid) {
607 if (EnumConst)
608 EnumConst->setInvalidDecl();
609 Enum->setInvalidDecl();
610 }
611
612 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000613 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
614
John McCall3b85ecf2010-01-23 22:37:59 +0000615 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000616 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000617 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000618 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000619
620 if (D->getDeclContext()->isFunctionOrMethod()) {
621 // If the enumeration is within a function or method, record the enum
622 // constant as a local.
623 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
624 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000625 }
626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000628 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000629 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000630 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000631 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000632 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000633 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000634
635 return Enum;
636}
637
Douglas Gregor6477b692009-03-25 15:04:13 +0000638Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
639 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
640 return 0;
641}
642
John McCalle29ba202009-08-20 01:44:21 +0000643Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000644 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
645
Douglas Gregor550d9b22009-10-31 17:21:17 +0000646 // Create a local instantiation scope for this class template, which
647 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000648 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000649 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000650 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000651 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000652 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000653
654 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000655
656 // Instantiate the qualifier. We have to do this first in case
657 // we're a friend declaration, because if we are then we need to put
658 // the new declaration in the appropriate context.
659 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
660 if (Qualifier) {
661 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
662 Pattern->getQualifierRange(),
663 TemplateArgs);
664 if (!Qualifier) return 0;
665 }
666
667 CXXRecordDecl *PrevDecl = 0;
668 ClassTemplateDecl *PrevClassTemplate = 0;
669
Nick Lewycky37574f52010-11-08 23:29:42 +0000670 if (!isFriend && Pattern->getPreviousDeclaration()) {
671 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
672 if (Found.first != Found.second) {
673 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
674 if (PrevClassTemplate)
675 PrevDecl = PrevClassTemplate->getTemplatedDecl();
676 }
677 }
678
John McCall93ba8572010-03-25 06:39:04 +0000679 // If this isn't a friend, then it's a member template, in which
680 // case we just want to build the instantiation in the
681 // specialization. If it is a friend, we want to build it in
682 // the appropriate context.
683 DeclContext *DC = Owner;
684 if (isFriend) {
685 if (Qualifier) {
686 CXXScopeSpec SS;
687 SS.setScopeRep(Qualifier);
688 SS.setRange(Pattern->getQualifierRange());
689 DC = SemaRef.computeDeclContext(SS);
690 if (!DC) return 0;
691 } else {
692 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
693 Pattern->getDeclContext(),
694 TemplateArgs);
695 }
696
697 // Look for a previous declaration of the template in the owning
698 // context.
699 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
700 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
701 SemaRef.LookupQualifiedName(R, DC);
702
703 if (R.isSingleResult()) {
704 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
705 if (PrevClassTemplate)
706 PrevDecl = PrevClassTemplate->getTemplatedDecl();
707 }
708
709 if (!PrevClassTemplate && Qualifier) {
710 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000711 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
712 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000713 return 0;
714 }
715
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000716 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000717 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000718 bool Complain = true;
719
720 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
721 // template for struct std::tr1::__detail::_Map_base, where the
722 // template parameters of the friend declaration don't match the
723 // template parameters of the original declaration. In this one
724 // case, we don't complain about the ill-formed friend
725 // declaration.
726 if (isFriend && Pattern->getIdentifier() &&
727 Pattern->getIdentifier()->isStr("_Map_base") &&
728 DC->isNamespace() &&
729 cast<NamespaceDecl>(DC)->getIdentifier() &&
730 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
731 DeclContext *DCParent = DC->getParent();
732 if (DCParent->isNamespace() &&
733 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
734 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
735 DeclContext *DCParent2 = DCParent->getParent();
736 if (DCParent2->isNamespace() &&
737 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
738 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
739 DCParent2->getParent()->isTranslationUnit())
740 Complain = false;
741 }
742 }
743
John McCall93ba8572010-03-25 06:39:04 +0000744 TemplateParameterList *PrevParams
745 = PrevClassTemplate->getTemplateParameters();
746
747 // Make sure the parameter lists match.
748 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000749 Complain,
750 Sema::TPL_TemplateMatch)) {
751 if (Complain)
752 return 0;
753
754 AdoptedPreviousTemplateParams = true;
755 InstParams = PrevParams;
756 }
John McCall93ba8572010-03-25 06:39:04 +0000757
758 // Do some additional validation, then merge default arguments
759 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000760 if (!AdoptedPreviousTemplateParams &&
761 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000762 Sema::TPC_ClassTemplate))
763 return 0;
764 }
765 }
766
John McCalle29ba202009-08-20 01:44:21 +0000767 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000768 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000769 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000770 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000771 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000772
John McCall93ba8572010-03-25 06:39:04 +0000773 if (Qualifier)
774 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000775
John McCalle29ba202009-08-20 01:44:21 +0000776 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000777 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
778 D->getIdentifier(), InstParams, RecordInst,
779 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000780 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000781
John McCall93ba8572010-03-25 06:39:04 +0000782 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000783 if (PrevClassTemplate)
784 Inst->setAccess(PrevClassTemplate->getAccess());
785 else
786 Inst->setAccess(D->getAccess());
787
John McCall93ba8572010-03-25 06:39:04 +0000788 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
789 // TODO: do we want to track the instantiation progeny of this
790 // friend target decl?
791 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000792 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000793 if (!PrevClassTemplate)
794 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000795 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000796
797 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000798 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000799 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000800
Douglas Gregor259571e2009-10-30 22:42:42 +0000801 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000802 if (isFriend) {
803 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000804 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000805 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000806
John McCalle29ba202009-08-20 01:44:21 +0000807 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000808
809 if (!PrevClassTemplate) {
810 // Queue up any out-of-line partial specializations of this member
811 // class template; the client will force their instantiation once
812 // the enclosing class has been instantiated.
813 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
814 D->getPartialSpecializations(PartialSpecs);
815 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
816 if (PartialSpecs[I]->isOutOfLine())
817 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
818 }
819
John McCalle29ba202009-08-20 01:44:21 +0000820 return Inst;
821}
822
Douglas Gregord60e1052009-08-27 16:57:43 +0000823Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000824TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
825 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000826 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
827
828 // Lookup the already-instantiated declaration in the instantiation
829 // of the class template and return that.
830 DeclContext::lookup_result Found
831 = Owner->lookup(ClassTemplate->getDeclName());
832 if (Found.first == Found.second)
833 return 0;
834
835 ClassTemplateDecl *InstClassTemplate
836 = dyn_cast<ClassTemplateDecl>(*Found.first);
837 if (!InstClassTemplate)
838 return 0;
839
Douglas Gregord65587f2010-11-10 19:44:59 +0000840 if (ClassTemplatePartialSpecializationDecl *Result
841 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
842 return Result;
843
844 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000845}
846
847Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000848TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000849 // Create a local instantiation scope for this function template, which
850 // will contain the instantiations of the template parameters and then get
851 // merged with the local instantiation scope for the function template
852 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000853 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000854
Douglas Gregord60e1052009-08-27 16:57:43 +0000855 TemplateParameterList *TempParams = D->getTemplateParameters();
856 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000857 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000858 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000859
Douglas Gregora735b202009-10-13 14:39:41 +0000860 FunctionDecl *Instantiated = 0;
861 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
862 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
863 InstParams));
864 else
865 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
866 D->getTemplatedDecl(),
867 InstParams));
868
869 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000870 return 0;
871
John McCall46460a62010-01-20 21:53:11 +0000872 Instantiated->setAccess(D->getAccess());
873
Mike Stump1eb44332009-09-09 15:08:12 +0000874 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000875 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000876 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000877 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000878 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000879 assert(InstTemplate &&
880 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000881
John McCallb1a56e72010-03-26 23:10:15 +0000882 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
883
John McCalle976ffe2009-12-14 23:19:40 +0000884 // Link the instantiation back to the pattern *unless* this is a
885 // non-definition friend declaration.
886 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000887 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000888 InstTemplate->setInstantiatedFromMemberTemplate(D);
889
John McCallb1a56e72010-03-26 23:10:15 +0000890 // Make declarations visible in the appropriate context.
891 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000892 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000893
Douglas Gregord60e1052009-08-27 16:57:43 +0000894 return InstTemplate;
895}
896
Douglas Gregord475b8d2009-03-25 21:17:03 +0000897Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
898 CXXRecordDecl *PrevDecl = 0;
899 if (D->isInjectedClassName())
900 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000901 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000902 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
903 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000904 TemplateArgs);
905 if (!Prev) return 0;
906 PrevDecl = cast<CXXRecordDecl>(Prev);
907 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000908
909 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000910 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000911 D->getLocation(), D->getIdentifier(),
912 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000913
914 // Substitute the nested name specifier, if any.
915 if (SubstQualifier(D, Record))
916 return 0;
917
Douglas Gregord475b8d2009-03-25 21:17:03 +0000918 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000919 // FIXME: Check against AS_none is an ugly hack to work around the issue that
920 // the tag decls introduced by friend class declarations don't have an access
921 // specifier. Remove once this area of the code gets sorted out.
922 if (D->getAccess() != AS_none)
923 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000924 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000925 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000926
John McCall02cace72009-08-28 07:59:38 +0000927 // If the original function was part of a friend declaration,
928 // inherit its namespace state.
929 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
930 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
931
Douglas Gregor9901c572010-05-21 00:31:19 +0000932 // Make sure that anonymous structs and unions are recorded.
933 if (D->isAnonymousStructOrUnion()) {
934 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000935 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000936 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
937 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000938
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000939 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000940 return Record;
941}
942
John McCall02cace72009-08-28 07:59:38 +0000943/// Normal class members are of more specific types and therefore
944/// don't make it here. This function serves two purposes:
945/// 1) instantiating function templates
946/// 2) substituting friend declarations
947/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000948Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000949 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000950 // Check whether there is already a function template specialization for
951 // this declaration.
952 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
953 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000954 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000955 std::pair<const TemplateArgument *, unsigned> Innermost
956 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000958 FunctionDecl *SpecFunc
959 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
960 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregor127102b2009-06-29 20:59:39 +0000962 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000963 if (SpecFunc)
964 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
John McCallb0cb0222010-03-27 05:57:59 +0000967 bool isFriend;
968 if (FunctionTemplate)
969 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
970 else
971 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
972
Douglas Gregor79c22782010-01-16 20:21:20 +0000973 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000974 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000975 !(isa<Decl>(Owner) &&
976 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000977 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregore53060f2009-06-25 22:08:12 +0000979 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000980 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
981 TInfo = SubstFunctionType(D, Params);
982 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000983 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000984 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000985
John McCalld325daa2010-03-26 04:53:08 +0000986 NestedNameSpecifier *Qualifier = D->getQualifier();
987 if (Qualifier) {
988 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
989 D->getQualifierRange(),
990 TemplateArgs);
991 if (!Qualifier) return 0;
992 }
993
John McCall68b6b872010-02-06 01:50:47 +0000994 // If we're instantiating a local function declaration, put the result
995 // in the owner; otherwise we need to find the instantiated context.
996 DeclContext *DC;
997 if (D->getDeclContext()->isFunctionOrMethod())
998 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000999 else if (isFriend && Qualifier) {
1000 CXXScopeSpec SS;
1001 SS.setScopeRep(Qualifier);
1002 SS.setRange(D->getQualifierRange());
1003 DC = SemaRef.computeDeclContext(SS);
1004 if (!DC) return 0;
1005 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001006 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1007 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001008 }
John McCall68b6b872010-02-06 01:50:47 +00001009
John McCall02cace72009-08-28 07:59:38 +00001010 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001011 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001012 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001013 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001014 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001015
John McCalld325daa2010-03-26 04:53:08 +00001016 if (Qualifier)
1017 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001018
John McCallb1a56e72010-03-26 23:10:15 +00001019 DeclContext *LexicalDC = Owner;
1020 if (!isFriend && D->isOutOfLine()) {
1021 assert(D->getDeclContext()->isFileContext());
1022 LexicalDC = D->getDeclContext();
1023 }
1024
1025 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Douglas Gregore53060f2009-06-25 22:08:12 +00001027 // Attach the parameters
1028 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001029 if (Params[P])
1030 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001031 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001032
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001033 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001034 if (TemplateParams) {
1035 // Our resulting instantiation is actually a function template, since we
1036 // are substituting only the outer template parameters. For example, given
1037 //
1038 // template<typename T>
1039 // struct X {
1040 // template<typename U> friend void f(T, U);
1041 // };
1042 //
1043 // X<int> x;
1044 //
1045 // We are instantiating the friend function template "f" within X<int>,
1046 // which means substituting int for T, but leaving "f" as a friend function
1047 // template.
1048 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001049 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001050 Function->getLocation(),
1051 Function->getDeclName(),
1052 TemplateParams, Function);
1053 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001054
1055 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001056
1057 if (isFriend && D->isThisDeclarationADefinition()) {
1058 // TODO: should we remember this connection regardless of whether
1059 // the friend declaration provided a body?
1060 FunctionTemplate->setInstantiatedFromMemberTemplate(
1061 D->getDescribedFunctionTemplate());
1062 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001063 } else if (FunctionTemplate) {
1064 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001065 std::pair<const TemplateArgument *, unsigned> Innermost
1066 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001067 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001068 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001069 Innermost.first,
1070 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001071 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001072 } else if (isFriend && D->isThisDeclarationADefinition()) {
1073 // TODO: should we remember this connection regardless of whether
1074 // the friend declaration provided a body?
1075 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001076 }
Douglas Gregora735b202009-10-13 14:39:41 +00001077
Douglas Gregore53060f2009-06-25 22:08:12 +00001078 if (InitFunctionInstantiation(Function, D))
1079 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Douglas Gregore53060f2009-06-25 22:08:12 +00001081 bool Redeclaration = false;
1082 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001083 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001084
John McCall68263142009-11-18 22:49:29 +00001085 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1086 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1087
John McCallaf2094e2010-04-08 09:05:18 +00001088 if (DependentFunctionTemplateSpecializationInfo *Info
1089 = D->getDependentSpecializationInfo()) {
1090 assert(isFriend && "non-friend has dependent specialization info?");
1091
1092 // This needs to be set now for future sanity.
1093 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1094
1095 // Instantiate the explicit template arguments.
1096 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1097 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001098 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1099 ExplicitArgs, TemplateArgs))
1100 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001101
1102 // Map the candidate templates to their instantiations.
1103 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1104 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1105 Info->getTemplate(I),
1106 TemplateArgs);
1107 if (!Temp) return 0;
1108
1109 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1110 }
1111
1112 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1113 &ExplicitArgs,
1114 Previous))
1115 Function->setInvalidDecl();
1116
1117 isExplicitSpecialization = true;
1118
1119 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001120 // Look only into the namespace where the friend would be declared to
1121 // find a previous declaration. This is the innermost enclosing namespace,
1122 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001123 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001124
Douglas Gregora735b202009-10-13 14:39:41 +00001125 // In C++, the previous declaration we find might be a tag type
1126 // (class or enum). In this case, the new declaration will hide the
1127 // tag type. Note that this does does not apply if we're declaring a
1128 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001129 if (Previous.isSingleTagDecl())
1130 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001131 }
1132
John McCall9f54ad42009-12-10 09:41:52 +00001133 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001134 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001135 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001136
John McCall76d32642010-04-24 01:30:58 +00001137 NamedDecl *PrincipalDecl = (TemplateParams
1138 ? cast<NamedDecl>(FunctionTemplate)
1139 : Function);
1140
Douglas Gregora735b202009-10-13 14:39:41 +00001141 // If the original function was part of a friend declaration,
1142 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001143 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001144 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001145 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001146 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001147 else
Douglas Gregora735b202009-10-13 14:39:41 +00001148 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001149
1150 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1151 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001152
Gabor Greif77535df2010-08-30 22:25:56 +00001153 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001154
Douglas Gregor238058c2010-05-18 05:45:02 +00001155 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1156 D->isThisDeclarationADefinition()) {
1157 // Check for a function body.
1158 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001159 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001160 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1161 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1162 << Function->getDeclName();
1163 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1164 Function->setInvalidDecl();
1165 }
1166 // Check for redefinitions due to other instantiations of this or
1167 // a similar friend function.
1168 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1169 REnd = Function->redecls_end();
1170 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001171 if (*R == Function)
1172 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001173 switch (R->getFriendObjectKind()) {
1174 case Decl::FOK_None:
1175 if (!queuedInstantiation && R->isUsed(false)) {
1176 if (MemberSpecializationInfo *MSInfo
1177 = Function->getMemberSpecializationInfo()) {
1178 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1179 SourceLocation Loc = R->getLocation(); // FIXME
1180 MSInfo->setPointOfInstantiation(Loc);
1181 SemaRef.PendingLocalImplicitInstantiations.push_back(
1182 std::make_pair(Function, Loc));
1183 queuedInstantiation = true;
1184 }
1185 }
1186 }
1187 break;
1188 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001189 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001190 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001191 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001192 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1193 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001194 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001195 Function->setInvalidDecl();
1196 break;
1197 }
1198 }
1199 }
1200 }
Douglas Gregora735b202009-10-13 14:39:41 +00001201 }
1202
John McCall76d32642010-04-24 01:30:58 +00001203 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1204 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1205 PrincipalDecl->setNonMemberOperator();
1206
Douglas Gregore53060f2009-06-25 22:08:12 +00001207 return Function;
1208}
1209
Douglas Gregord60e1052009-08-27 16:57:43 +00001210Decl *
1211TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1212 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001213 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1214 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001215 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001216 // We are creating a function template specialization from a function
1217 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001218 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001219 std::pair<const TemplateArgument *, unsigned> Innermost
1220 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001222 FunctionDecl *SpecFunc
1223 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1224 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Douglas Gregor6b906862009-08-21 00:16:32 +00001226 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001227 if (SpecFunc)
1228 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001229 }
1230
John McCallb0cb0222010-03-27 05:57:59 +00001231 bool isFriend;
1232 if (FunctionTemplate)
1233 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1234 else
1235 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1236
Douglas Gregor79c22782010-01-16 20:21:20 +00001237 bool MergeWithParentScope = (TemplateParams != 0) ||
1238 !(isa<Decl>(Owner) &&
1239 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001240 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001241
John McCall4eab39f2010-10-19 02:26:41 +00001242 // Instantiate enclosing template arguments for friends.
1243 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1244 unsigned NumTempParamLists = 0;
1245 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1246 TempParamLists.set_size(NumTempParamLists);
1247 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1248 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1249 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1250 if (!InstParams)
1251 return NULL;
1252 TempParamLists[I] = InstParams;
1253 }
1254 }
1255
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001256 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001257 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1258 TInfo = SubstFunctionType(D, Params);
1259 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001260 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001261 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001262
Abramo Bagnara723df242010-12-14 22:11:44 +00001263 // \brief If the type of this function, after ignoring parentheses,
1264 // is not *directly* a function type, then we're instantiating a function
1265 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001266 //
1267 // typedef int functype(int, int);
1268 // functype func;
1269 //
1270 // In this case, we'll just go instantiate the ParmVarDecls that we
1271 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001272 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001273 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001274 llvm::SmallVector<QualType, 4> ParamTypes;
1275 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1276 D->getNumParams(), TemplateArgs, ParamTypes,
1277 &Params))
1278 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001279 }
1280
John McCallb0cb0222010-03-27 05:57:59 +00001281 NestedNameSpecifier *Qualifier = D->getQualifier();
1282 if (Qualifier) {
1283 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1284 D->getQualifierRange(),
1285 TemplateArgs);
1286 if (!Qualifier) return 0;
1287 }
1288
1289 DeclContext *DC = Owner;
1290 if (isFriend) {
1291 if (Qualifier) {
1292 CXXScopeSpec SS;
1293 SS.setScopeRep(Qualifier);
1294 SS.setRange(D->getQualifierRange());
1295 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001296
1297 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1298 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001299 } else {
1300 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1301 D->getDeclContext(),
1302 TemplateArgs);
1303 }
1304 if (!DC) return 0;
1305 }
1306
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001307 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001308 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001309 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Abramo Bagnara25777432010-08-11 22:01:17 +00001311 DeclarationNameInfo NameInfo
1312 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001313 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001314 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001315 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001316 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001317 Constructor->isInlineSpecified(),
1318 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001319 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001320 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Craig Silversteinb41d8992010-10-21 00:44:50 +00001321 NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001322 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001323 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001324 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001325 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001326 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001327 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001328 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001329 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001330 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1331 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001332 D->isStatic(),
1333 D->getStorageClassAsWritten(),
1334 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001335 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001336
John McCallb0cb0222010-03-27 05:57:59 +00001337 if (Qualifier)
1338 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001339
Douglas Gregord60e1052009-08-27 16:57:43 +00001340 if (TemplateParams) {
1341 // Our resulting instantiation is actually a function template, since we
1342 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001343 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001344 // template<typename T>
1345 // struct X {
1346 // template<typename U> void f(T, U);
1347 // };
1348 //
1349 // X<int> x;
1350 //
1351 // We are instantiating the member template "f" within X<int>, which means
1352 // substituting int for T, but leaving "f" as a member function template.
1353 // Build the function template itself.
1354 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1355 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001356 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001357 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001358 if (isFriend) {
1359 FunctionTemplate->setLexicalDeclContext(Owner);
1360 FunctionTemplate->setObjectOfFriendDecl(true);
1361 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001362 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001363 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001364 } else if (FunctionTemplate) {
1365 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001366 std::pair<const TemplateArgument *, unsigned> Innermost
1367 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001368 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001369 TemplateArgumentList::CreateCopy(SemaRef.Context,
1370 Innermost.first,
1371 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001372 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001373 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001374 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001375 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001376 }
1377
Mike Stump1eb44332009-09-09 15:08:12 +00001378 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001379 // out-of-line, the instantiation will have the same lexical
1380 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001381 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001382 if (NumTempParamLists)
1383 Method->setTemplateParameterListsInfo(SemaRef.Context,
1384 NumTempParamLists,
1385 TempParamLists.data());
1386
John McCallb0cb0222010-03-27 05:57:59 +00001387 Method->setLexicalDeclContext(Owner);
1388 Method->setObjectOfFriendDecl(true);
1389 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001390 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Douglas Gregor5545e162009-03-24 00:38:23 +00001392 // Attach the parameters
1393 for (unsigned P = 0; P < Params.size(); ++P)
1394 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001395 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001396
1397 if (InitMethodInstantiation(Method, D))
1398 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001399
Abramo Bagnara25777432010-08-11 22:01:17 +00001400 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1401 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
John McCallb0cb0222010-03-27 05:57:59 +00001403 if (!FunctionTemplate || TemplateParams || isFriend) {
1404 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregordec06662009-08-21 18:42:58 +00001406 // In C++, the previous declaration we find might be a tag type
1407 // (class or enum). In this case, the new declaration will hide the
1408 // tag type. Note that this does does not apply if we're declaring a
1409 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001410 if (Previous.isSingleTagDecl())
1411 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001412 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001413
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001414 bool Redeclaration = false;
1415 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001416 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001417 /*FIXME:*/OverloadableAttrRequired);
1418
Douglas Gregor4ba31362009-12-01 17:24:26 +00001419 if (D->isPure())
1420 SemaRef.CheckPureMethod(Method, SourceRange());
1421
John McCall46460a62010-01-20 21:53:11 +00001422 Method->setAccess(D->getAccess());
1423
John McCallb0cb0222010-03-27 05:57:59 +00001424 if (FunctionTemplate) {
1425 // If there's a function template, let our caller handle it.
1426 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1427 // Don't hide a (potentially) valid declaration with an invalid one.
1428 } else {
1429 NamedDecl *DeclToAdd = (TemplateParams
1430 ? cast<NamedDecl>(FunctionTemplate)
1431 : Method);
1432 if (isFriend)
1433 Record->makeDeclVisibleInContext(DeclToAdd);
1434 else
1435 Owner->addDecl(DeclToAdd);
1436 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001437
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001438 return Method;
1439}
1440
Douglas Gregor615c5d42009-03-24 16:43:20 +00001441Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001442 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001443}
1444
Douglas Gregor03b2b072009-03-24 00:15:49 +00001445Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001446 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001447}
1448
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001449Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001450 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001451}
1452
Douglas Gregor6477b692009-03-25 15:04:13 +00001453ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001454 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001455}
1456
John McCalle29ba202009-08-20 01:44:21 +00001457Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1458 TemplateTypeParmDecl *D) {
1459 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001460 const Type* T = D->getTypeForDecl();
1461 assert(T->isTemplateTypeParmType());
1462 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001463
John McCalle29ba202009-08-20 01:44:21 +00001464 TemplateTypeParmDecl *Inst =
1465 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001466 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001467 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001468 D->wasDeclaredWithTypename(),
1469 D->isParameterPack());
1470
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001471 if (D->hasDefaultArgument())
1472 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001473
Douglas Gregor550d9b22009-10-31 17:21:17 +00001474 // Introduce this template parameter's instantiation into the instantiation
1475 // scope.
1476 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1477
John McCalle29ba202009-08-20 01:44:21 +00001478 return Inst;
1479}
1480
Douglas Gregor33642df2009-10-23 23:25:44 +00001481Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1482 NonTypeTemplateParmDecl *D) {
1483 // Substitute into the type of the non-type template parameter.
1484 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001485 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001486 if (DI) {
1487 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1488 D->getDeclName());
1489 if (DI) T = DI->getType();
1490 } else {
1491 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1492 D->getDeclName());
1493 DI = 0;
1494 }
1495 if (T.isNull())
1496 return 0;
1497
1498 // Check that this type is acceptable for a non-type template parameter.
1499 bool Invalid = false;
1500 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1501 if (T.isNull()) {
1502 T = SemaRef.Context.IntTy;
1503 Invalid = true;
1504 }
1505
Douglas Gregor10738d32010-12-23 23:51:58 +00001506 // FIXME: Variadic templates.
Douglas Gregor33642df2009-10-23 23:25:44 +00001507 NonTypeTemplateParmDecl *Param
1508 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001509 D->getDepth() - TemplateArgs.getNumLevels(),
1510 D->getPosition(), D->getIdentifier(), T,
Douglas Gregor10738d32010-12-23 23:51:58 +00001511 D->isParameterPack(), DI);
Douglas Gregor33642df2009-10-23 23:25:44 +00001512 if (Invalid)
1513 Param->setInvalidDecl();
1514
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001515 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001516
1517 // Introduce this template parameter's instantiation into the instantiation
1518 // scope.
1519 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001520 return Param;
1521}
1522
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001523Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001524TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1525 TemplateTemplateParmDecl *D) {
1526 // Instantiate the template parameter list of the template template parameter.
1527 TemplateParameterList *TempParams = D->getTemplateParameters();
1528 TemplateParameterList *InstParams;
1529 {
1530 // Perform the actual substitution of template parameters within a new,
1531 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001532 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001533 InstParams = SubstTemplateParams(TempParams);
1534 if (!InstParams)
1535 return NULL;
1536 }
1537
1538 // Build the template template parameter.
1539 TemplateTemplateParmDecl *Param
1540 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001541 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001542 D->getPosition(), D->isParameterPack(),
1543 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001544 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001545
Douglas Gregor9106ef72009-11-11 16:58:32 +00001546 // Introduce this template parameter's instantiation into the instantiation
1547 // scope.
1548 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1549
1550 return Param;
1551}
1552
Douglas Gregor48c32a72009-11-17 06:07:40 +00001553Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1554 // Using directives are never dependent, so they require no explicit
1555
1556 UsingDirectiveDecl *Inst
1557 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1558 D->getNamespaceKeyLocation(),
1559 D->getQualifierRange(), D->getQualifier(),
1560 D->getIdentLocation(),
1561 D->getNominatedNamespace(),
1562 D->getCommonAncestor());
1563 Owner->addDecl(Inst);
1564 return Inst;
1565}
1566
John McCalled976492009-12-04 22:46:56 +00001567Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001568
1569 // The nested name specifier may be dependent, for example
1570 // template <typename T> struct t {
1571 // struct s1 { T f1(); };
1572 // struct s2 : s1 { using s1::f1; };
1573 // };
1574 // template struct t<int>;
1575 // Here, in using s1::f1, s1 refers to t<T>::s1;
1576 // we need to substitute for t<int>::s1.
1577 NestedNameSpecifier *NNS =
1578 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1579 D->getNestedNameRange(),
1580 TemplateArgs);
1581 if (!NNS)
1582 return 0;
1583
1584 // The name info is non-dependent, so no transformation
1585 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001586 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001587
John McCall9f54ad42009-12-10 09:41:52 +00001588 // We only need to do redeclaration lookups if we're in a class
1589 // scope (in fact, it's not really even possible in non-class
1590 // scopes).
1591 bool CheckRedeclaration = Owner->isRecord();
1592
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001593 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1594 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001595
John McCalled976492009-12-04 22:46:56 +00001596 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001597 D->getNestedNameRange(),
1598 D->getUsingLocation(),
Douglas Gregor1b398202010-09-29 17:58:28 +00001599 NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001600 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001601 D->isTypeName());
1602
1603 CXXScopeSpec SS;
Douglas Gregor1b398202010-09-29 17:58:28 +00001604 SS.setScopeRep(NNS);
John McCalled976492009-12-04 22:46:56 +00001605 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001606
1607 if (CheckRedeclaration) {
1608 Prev.setHideTags(false);
1609 SemaRef.LookupQualifiedName(Prev, Owner);
1610
1611 // Check for invalid redeclarations.
1612 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1613 D->isTypeName(), SS,
1614 D->getLocation(), Prev))
1615 NewUD->setInvalidDecl();
1616
1617 }
1618
1619 if (!NewUD->isInvalidDecl() &&
1620 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001621 D->getLocation()))
1622 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001623
John McCalled976492009-12-04 22:46:56 +00001624 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1625 NewUD->setAccess(D->getAccess());
1626 Owner->addDecl(NewUD);
1627
John McCall9f54ad42009-12-10 09:41:52 +00001628 // Don't process the shadow decls for an invalid decl.
1629 if (NewUD->isInvalidDecl())
1630 return NewUD;
1631
John McCall323c3102009-12-22 22:26:37 +00001632 bool isFunctionScope = Owner->isFunctionOrMethod();
1633
John McCall9f54ad42009-12-10 09:41:52 +00001634 // Process the shadow decls.
1635 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1636 I != E; ++I) {
1637 UsingShadowDecl *Shadow = *I;
1638 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001639 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1640 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001641 TemplateArgs));
1642
1643 if (CheckRedeclaration &&
1644 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1645 continue;
1646
1647 UsingShadowDecl *InstShadow
1648 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1649 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001650
1651 if (isFunctionScope)
1652 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001653 }
John McCalled976492009-12-04 22:46:56 +00001654
1655 return NewUD;
1656}
1657
1658Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001659 // Ignore these; we handle them in bulk when processing the UsingDecl.
1660 return 0;
John McCalled976492009-12-04 22:46:56 +00001661}
1662
John McCall7ba107a2009-11-18 02:36:19 +00001663Decl * TemplateDeclInstantiator
1664 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001665 NestedNameSpecifier *NNS =
1666 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1667 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001668 TemplateArgs);
1669 if (!NNS)
1670 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001672 CXXScopeSpec SS;
1673 SS.setRange(D->getTargetNestedNameRange());
1674 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001676 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1677 // Hence, no tranformation is required for it.
1678 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001679 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001680 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001681 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001682 /*instantiation*/ true,
1683 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001684 if (UD)
John McCalled976492009-12-04 22:46:56 +00001685 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1686
John McCall7ba107a2009-11-18 02:36:19 +00001687 return UD;
1688}
1689
1690Decl * TemplateDeclInstantiator
1691 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1692 NestedNameSpecifier *NNS =
1693 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1694 D->getTargetNestedNameRange(),
1695 TemplateArgs);
1696 if (!NNS)
1697 return 0;
1698
1699 CXXScopeSpec SS;
1700 SS.setRange(D->getTargetNestedNameRange());
1701 SS.setScopeRep(NNS);
1702
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001703 DeclarationNameInfo NameInfo
1704 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1705
John McCall7ba107a2009-11-18 02:36:19 +00001706 NamedDecl *UD =
1707 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001708 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001709 /*instantiation*/ true,
1710 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001711 if (UD)
John McCalled976492009-12-04 22:46:56 +00001712 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1713
Anders Carlsson0d8df782009-08-29 19:37:28 +00001714 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001715}
1716
John McCallce3ff2b2009-08-25 22:02:44 +00001717Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001718 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001719 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001720 if (D->isInvalidDecl())
1721 return 0;
1722
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001723 return Instantiator.Visit(D);
1724}
1725
John McCalle29ba202009-08-20 01:44:21 +00001726/// \brief Instantiates a nested template parameter list in the current
1727/// instantiation context.
1728///
1729/// \param L The parameter list to instantiate
1730///
1731/// \returns NULL if there was an error
1732TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001733TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001734 // Get errors for all the parameters before bailing out.
1735 bool Invalid = false;
1736
1737 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001738 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001739 ParamVector Params;
1740 Params.reserve(N);
1741 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1742 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001743 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001744 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001745 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001746 }
1747
1748 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001749 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001750 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001751
1752 TemplateParameterList *InstL
1753 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1754 L->getLAngleLoc(), &Params.front(), N,
1755 L->getRAngleLoc());
1756 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001757}
John McCalle29ba202009-08-20 01:44:21 +00001758
Douglas Gregored9c0f92009-10-29 00:04:11 +00001759/// \brief Instantiate the declaration of a class template partial
1760/// specialization.
1761///
1762/// \param ClassTemplate the (instantiated) class template that is partially
1763// specialized by the instantiation of \p PartialSpec.
1764///
1765/// \param PartialSpec the (uninstantiated) class template partial
1766/// specialization that we are instantiating.
1767///
Douglas Gregord65587f2010-11-10 19:44:59 +00001768/// \returns The instantiated partial specialization, if successful; otherwise,
1769/// NULL to indicate an error.
1770ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001771TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1772 ClassTemplateDecl *ClassTemplate,
1773 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001774 // Create a local instantiation scope for this class template partial
1775 // specialization, which will contain the instantiations of the template
1776 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001777 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001778
Douglas Gregored9c0f92009-10-29 00:04:11 +00001779 // Substitute into the template parameters of the class template partial
1780 // specialization.
1781 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1782 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1783 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001784 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001785
1786 // Substitute into the template arguments of the class template partial
1787 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001788 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001789 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1790 PartialSpec->getNumTemplateArgsAsWritten(),
1791 InstTemplateArgs, TemplateArgs))
1792 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001793
Douglas Gregored9c0f92009-10-29 00:04:11 +00001794 // Check that the template argument list is well-formed for this
1795 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001796 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001797 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1798 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001799 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001800 false,
1801 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001802 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001803
1804 // Figure out where to insert this class template partial specialization
1805 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001806 void *InsertPos = 0;
1807 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001808 = ClassTemplate->findPartialSpecialization(Converted.data(),
1809 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001810
1811 // Build the canonical type that describes the converted template
1812 // arguments of the class template partial specialization.
1813 QualType CanonType
1814 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001815 Converted.data(),
1816 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001817
1818 // Build the fully-sugared type for this class template
1819 // specialization as the user wrote in the specialization
1820 // itself. This means that we'll pretty-print the type retrieved
1821 // from the specialization's declaration the way that the user
1822 // actually wrote the specialization, rather than formatting the
1823 // name based on the "canonical" representation used to store the
1824 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001825 TypeSourceInfo *WrittenTy
1826 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1827 TemplateName(ClassTemplate),
1828 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001829 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001830 CanonType);
1831
1832 if (PrevDecl) {
1833 // We've already seen a partial specialization with the same template
1834 // parameters and template arguments. This can happen, for example, when
1835 // substituting the outer template arguments ends up causing two
1836 // class template partial specializations of a member class template
1837 // to have identical forms, e.g.,
1838 //
1839 // template<typename T, typename U>
1840 // struct Outer {
1841 // template<typename X, typename Y> struct Inner;
1842 // template<typename Y> struct Inner<T, Y>;
1843 // template<typename Y> struct Inner<U, Y>;
1844 // };
1845 //
1846 // Outer<int, int> outer; // error: the partial specializations of Inner
1847 // // have the same signature.
1848 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001849 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001850 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1851 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001852 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001853 }
1854
1855
1856 // Create the class template partial specialization declaration.
1857 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001858 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1859 PartialSpec->getTagKind(),
1860 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001861 PartialSpec->getLocation(),
1862 InstParams,
1863 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001864 Converted.data(),
1865 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001866 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001867 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001868 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001869 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001870 // Substitute the nested name specifier, if any.
1871 if (SubstQualifier(PartialSpec, InstPartialSpec))
1872 return 0;
1873
Douglas Gregored9c0f92009-10-29 00:04:11 +00001874 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001875 InstPartialSpec->setTypeAsWritten(WrittenTy);
1876
Douglas Gregored9c0f92009-10-29 00:04:11 +00001877 // Add this partial specialization to the set of class template partial
1878 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001879 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001880 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001881}
1882
John McCall21ef0fa2010-03-11 09:03:00 +00001883TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001884TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001885 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001886 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1887 assert(OldTInfo && "substituting function without type source info");
1888 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001889 TypeSourceInfo *NewTInfo
1890 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1891 D->getTypeSpecStartLoc(),
1892 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001893 if (!NewTInfo)
1894 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001895
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001896 if (NewTInfo != OldTInfo) {
1897 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001898 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001899 if (FunctionProtoTypeLoc *OldProtoLoc
1900 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001901 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001902 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1903 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001904 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
1905 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
1906 OldIdx != NumOldParams; ++OldIdx) {
1907 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
1908 if (!OldParam->isParameterPack() ||
1909 (NewIdx < NumNewParams &&
1910 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
1911 // Simple case: normal parameter, or a parameter pack that's
1912 // instantiated to a (still-dependent) parameter pack.
1913 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
1914 Params.push_back(NewParam);
1915 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
1916 NewParam);
1917 continue;
1918 }
1919
1920 // Parameter pack: make the instantiation an argument pack.
1921 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
1922 OldParam);
1923 while (NewIdx < NumNewParams) {
1924 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
1925 Params.push_back(NewParam);
1926 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
1927 NewParam);
1928 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001929 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001930 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001931 } else {
1932 // The function type itself was not dependent and therefore no
1933 // substitution occurred. However, we still need to instantiate
1934 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00001935 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001936 if (FunctionProtoTypeLoc *OldProtoLoc
1937 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1938 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1939 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1940 if (!Parm)
1941 return 0;
1942 Params.push_back(Parm);
1943 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001944 }
1945 }
John McCall21ef0fa2010-03-11 09:03:00 +00001946 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001947}
1948
Mike Stump1eb44332009-09-09 15:08:12 +00001949/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001950/// declaration (New) from the corresponding fields of its template (Tmpl).
1951///
1952/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001953bool
1954TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001955 FunctionDecl *Tmpl) {
1956 if (Tmpl->isDeleted())
1957 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregorcca9e962009-07-01 22:01:06 +00001959 // If we are performing substituting explicitly-specified template arguments
1960 // or deduced template arguments into a function template and we reach this
1961 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001962 // to keeping the new function template specialization. We therefore
1963 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001964 // into a template instantiation for this specific function template
1965 // specialization, which is not a SFINAE context, so that we diagnose any
1966 // further errors in the declaration itself.
1967 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1968 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1969 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1970 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001971 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001972 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001973 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001974 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001975 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001976 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1977 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001978 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001979 }
1980 }
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001982 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1983 assert(Proto && "Function template without prototype?");
1984
1985 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1986 Proto->getNoReturnAttr()) {
1987 // The function has an exception specification or a "noreturn"
1988 // attribute. Substitute into each of the exception types.
1989 llvm::SmallVector<QualType, 4> Exceptions;
1990 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1991 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00001992 if (const PackExpansionType *PackExpansion
1993 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
1994 // We have a pack expansion. Instantiate it.
1995 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1996 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
1997 Unexpanded);
1998 assert(!Unexpanded.empty() &&
1999 "Pack expansion without parameter packs?");
2000
2001 bool Expand = false;
2002 unsigned NumExpansions = 0;
2003 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2004 SourceRange(),
2005 Unexpanded.data(),
2006 Unexpanded.size(),
2007 TemplateArgs,
2008 Expand, NumExpansions))
2009 break;
2010
2011 if (!Expand) {
2012 // We can't expand this pack expansion into separate arguments yet;
2013 // just substitute into the argument pack.
2014 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2015 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2016 TemplateArgs,
2017 New->getLocation(), New->getDeclName());
2018 if (T.isNull())
2019 break;
2020
2021 Exceptions.push_back(T);
2022 continue;
2023 }
2024
2025 // Substitute into the pack expansion pattern for each template
2026 bool Invalid = false;
2027 for (unsigned ArgIdx = 0; ArgIdx != NumExpansions; ++ArgIdx) {
2028 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2029
2030 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2031 TemplateArgs,
2032 New->getLocation(), New->getDeclName());
2033 if (T.isNull()) {
2034 Invalid = true;
2035 break;
2036 }
2037
2038 Exceptions.push_back(T);
2039 }
2040
2041 if (Invalid)
2042 break;
2043
2044 continue;
2045 }
2046
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002047 QualType T
2048 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2049 New->getLocation(), New->getDeclName());
2050 if (T.isNull() ||
2051 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2052 continue;
2053
2054 Exceptions.push_back(T);
2055 }
2056
2057 // Rebuild the function type
2058
John McCalle23cf432010-12-14 08:05:40 +00002059 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2060 EPI.HasExceptionSpec = Proto->hasExceptionSpec();
2061 EPI.HasAnyExceptionSpec = Proto->hasAnyExceptionSpec();
2062 EPI.NumExceptions = Exceptions.size();
2063 EPI.Exceptions = Exceptions.data();
2064 EPI.ExtInfo = Proto->getExtInfo();
2065
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002066 const FunctionProtoType *NewProto
2067 = New->getType()->getAs<FunctionProtoType>();
2068 assert(NewProto && "Template instantiation without function prototype?");
2069 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2070 NewProto->arg_type_begin(),
2071 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002072 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002073 }
2074
John McCall1d8d1cc2010-08-01 02:01:53 +00002075 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002076
Douglas Gregore53060f2009-06-25 22:08:12 +00002077 return false;
2078}
2079
Douglas Gregor5545e162009-03-24 00:38:23 +00002080/// \brief Initializes common fields of an instantiated method
2081/// declaration (New) from the corresponding fields of its template
2082/// (Tmpl).
2083///
2084/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002085bool
2086TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002087 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002088 if (InitFunctionInstantiation(New, Tmpl))
2089 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor5545e162009-03-24 00:38:23 +00002091 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002092 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002093 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002094
2095 // FIXME: attributes
2096 // FIXME: New needs a pointer to Tmpl
2097 return false;
2098}
Douglas Gregora58861f2009-05-13 20:28:22 +00002099
2100/// \brief Instantiate the definition of the given function from its
2101/// template.
2102///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002103/// \param PointOfInstantiation the point at which the instantiation was
2104/// required. Note that this is not precisely a "point of instantiation"
2105/// for the function, but it's close.
2106///
Douglas Gregora58861f2009-05-13 20:28:22 +00002107/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002108/// function template specialization or member function of a class template
2109/// specialization.
2110///
2111/// \param Recursive if true, recursively instantiates any functions that
2112/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002113///
2114/// \param DefinitionRequired if true, then we are performing an explicit
2115/// instantiation where the body of the function is required. Complain if
2116/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002117void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002118 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002119 bool Recursive,
2120 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002121 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002122 return;
2123
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002124 // Never instantiate an explicit specialization.
2125 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2126 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002127
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002128 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002129 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002130 Stmt *Pattern = 0;
2131 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002132 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002133
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002134 if (!Pattern) {
2135 if (DefinitionRequired) {
2136 if (Function->getPrimaryTemplate())
2137 Diag(PointOfInstantiation,
2138 diag::err_explicit_instantiation_undefined_func_template)
2139 << Function->getPrimaryTemplate();
2140 else
2141 Diag(PointOfInstantiation,
2142 diag::err_explicit_instantiation_undefined_member)
2143 << 1 << Function->getDeclName() << Function->getDeclContext();
2144
2145 if (PatternDecl)
2146 Diag(PatternDecl->getLocation(),
2147 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002148 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002149 } else if (Function->getTemplateSpecializationKind()
2150 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002151 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002152 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002153 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002154
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002155 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002156 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002157
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002158 // C++0x [temp.explicit]p9:
2159 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002160 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002161 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002162 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002163 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002164 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002165 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002167 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2168 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002169 return;
2170
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002171 // If we're performing recursive template instantiation, create our own
2172 // queue of pending implicit instantiations that we will instantiate later,
2173 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002174 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002175 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002176 if (Recursive) {
2177 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002178 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002179 }
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Douglas Gregor9679caf2010-05-12 17:27:19 +00002181 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002182 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002183 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002184
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002185 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002186 // recorded, unless we're actually a member function within a local
2187 // class, in which case we need to merge our results with the parent
2188 // scope (of the enclosing function).
2189 bool MergeWithParentScope = false;
2190 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2191 MergeWithParentScope = Rec->isLocalClass();
2192
2193 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002195 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002196 // instantiation scope, and set the parameter names to those used
2197 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002198 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002199 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2200 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002201 if (!PatternParam->isParameterPack()) {
2202 // Simple case: not a parameter pack.
2203 assert(FParamIdx < Function->getNumParams());
2204 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2205 FunctionParam->setDeclName(PatternParam->getDeclName());
2206 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2207 ++FParamIdx;
2208 continue;
2209 }
2210
2211 // Expand the parameter pack.
2212 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2213 for (unsigned NumFParams = Function->getNumParams();
2214 FParamIdx < NumFParams;
2215 ++FParamIdx) {
2216 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2217 FunctionParam->setDeclName(PatternParam->getDeclName());
2218 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2219 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002220 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002221
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002222 // Enter the scope of this instantiation. We don't use
2223 // PushDeclContext because we don't have a scope.
2224 DeclContext *PreviousContext = CurContext;
2225 CurContext = Function;
2226
Mike Stump1eb44332009-09-09 15:08:12 +00002227 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002228 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002229
2230 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002231 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002232 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2233 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2234 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002235 }
2236
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002237 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002238 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002239
Douglas Gregor52604ab2009-09-11 21:19:12 +00002240 if (Body.isInvalid())
2241 Function->setInvalidDecl();
2242
John McCall9ae2f072010-08-23 23:25:46 +00002243 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002244 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002245
John McCall0c01d182010-03-24 05:22:00 +00002246 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2247
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002248 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002249
2250 DeclGroupRef DG(Function);
2251 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Douglas Gregor60406be2010-01-16 22:29:39 +00002253 // This class may have local implicit instantiations that need to be
2254 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002255 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002256 Scope.Exit();
2257
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002258 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002259 // Define any pending vtables.
2260 DefineUsedVTables();
2261
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002262 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002263 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002264 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002266 // Restore the set of pending vtables.
2267 VTableUses.swap(SavedVTableUses);
2268
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002269 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002270 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002271 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002272}
2273
2274/// \brief Instantiate the definition of the given variable from its
2275/// template.
2276///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002277/// \param PointOfInstantiation the point at which the instantiation was
2278/// required. Note that this is not precisely a "point of instantiation"
2279/// for the function, but it's close.
2280///
2281/// \param Var the already-instantiated declaration of a static member
2282/// variable of a class template specialization.
2283///
2284/// \param Recursive if true, recursively instantiates any functions that
2285/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002286///
2287/// \param DefinitionRequired if true, then we are performing an explicit
2288/// instantiation where an out-of-line definition of the member variable
2289/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002290void Sema::InstantiateStaticDataMemberDefinition(
2291 SourceLocation PointOfInstantiation,
2292 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002293 bool Recursive,
2294 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002295 if (Var->isInvalidDecl())
2296 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Douglas Gregor7caa6822009-07-24 20:34:43 +00002298 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002299 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002300 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002301 assert(Def->isStaticDataMember() && "Not a static data member?");
2302 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Douglas Gregor0d035142009-10-27 18:42:08 +00002304 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002305 // We did not find an out-of-line definition of this static data member,
2306 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002307 // instantiate this definition (or provide a specialization for it) in
2308 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002309 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002310 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002311 Diag(PointOfInstantiation,
2312 diag::err_explicit_instantiation_undefined_member)
2313 << 2 << Var->getDeclName() << Var->getDeclContext();
2314 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002315 } else if (Var->getTemplateSpecializationKind()
2316 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002317 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002318 std::make_pair(Var, PointOfInstantiation));
2319 }
2320
Douglas Gregor7caa6822009-07-24 20:34:43 +00002321 return;
2322 }
2323
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002324 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002325 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002326 return;
2327
2328 // C++0x [temp.explicit]p9:
2329 // Except for inline functions, other explicit instantiation declarations
2330 // have the effect of suppressing the implicit instantiation of the entity
2331 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002332 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002333 == TSK_ExplicitInstantiationDeclaration)
2334 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002335
Douglas Gregor7caa6822009-07-24 20:34:43 +00002336 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2337 if (Inst)
2338 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Douglas Gregor7caa6822009-07-24 20:34:43 +00002340 // If we're performing recursive template instantiation, create our own
2341 // queue of pending implicit instantiations that we will instantiate later,
2342 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002343 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002344 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002345 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Douglas Gregor7caa6822009-07-24 20:34:43 +00002347 // Enter the scope of this instantiation. We don't use
2348 // PushDeclContext because we don't have a scope.
2349 DeclContext *PreviousContext = CurContext;
2350 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002352 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002353 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002354 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002355 CurContext = PreviousContext;
2356
2357 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002358 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2359 assert(MSInfo && "Missing member specialization information?");
2360 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2361 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002362 DeclGroupRef DG(Var);
2363 Consumer.HandleTopLevelDecl(DG);
2364 }
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Douglas Gregor7caa6822009-07-24 20:34:43 +00002366 if (Recursive) {
2367 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002368 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002369 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Douglas Gregor7caa6822009-07-24 20:34:43 +00002371 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002372 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002373 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002374}
Douglas Gregor815215d2009-05-27 05:35:12 +00002375
Anders Carlsson09025312009-08-29 05:16:22 +00002376void
2377Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2378 const CXXConstructorDecl *Tmpl,
2379 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Anders Carlsson09025312009-08-29 05:16:22 +00002381 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002382 bool AnyErrors = false;
2383
Anders Carlsson09025312009-08-29 05:16:22 +00002384 // Instantiate all the initializers.
2385 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002386 InitsEnd = Tmpl->init_end();
2387 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002388 CXXBaseOrMemberInitializer *Init = *Inits;
2389
Chandler Carruth030ef472010-09-03 21:54:20 +00002390 // Only instantiate written initializers, let Sema re-construct implicit
2391 // ones.
2392 if (!Init->isWritten())
2393 continue;
2394
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002395 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002396 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002398 SourceLocation EllipsisLoc;
2399
2400 if (Init->isPackExpansion()) {
2401 // This is a pack expansion. We should expand it now.
2402 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2403 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2404 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2405 bool ShouldExpand = false;
2406 unsigned NumExpansions = 0;
2407 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2408 BaseTL.getSourceRange(),
2409 Unexpanded.data(),
2410 Unexpanded.size(),
2411 TemplateArgs, ShouldExpand,
2412 NumExpansions)) {
2413 AnyErrors = true;
2414 New->setInvalidDecl();
2415 continue;
2416 }
2417 assert(ShouldExpand && "Partial instantiation of base initializer?");
2418
2419 // Loop over all of the arguments in the argument pack(s),
2420 for (unsigned I = 0; I != NumExpansions; ++I) {
2421 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2422
2423 // Instantiate the initializer.
2424 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2425 LParenLoc, NewArgs, RParenLoc)) {
2426 AnyErrors = true;
2427 break;
2428 }
2429
2430 // Instantiate the base type.
2431 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2432 TemplateArgs,
2433 Init->getSourceLocation(),
2434 New->getDeclName());
2435 if (!BaseTInfo) {
2436 AnyErrors = true;
2437 break;
2438 }
2439
2440 // Build the initializer.
2441 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2442 BaseTInfo,
2443 (Expr **)NewArgs.data(),
2444 NewArgs.size(),
2445 Init->getLParenLoc(),
2446 Init->getRParenLoc(),
2447 New->getParent(),
2448 SourceLocation());
2449 if (NewInit.isInvalid()) {
2450 AnyErrors = true;
2451 break;
2452 }
2453
2454 NewInits.push_back(NewInit.get());
2455 NewArgs.clear();
2456 }
2457
2458 continue;
2459 }
2460
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002461 // Instantiate the initializer.
2462 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002463 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002464 AnyErrors = true;
2465 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002466 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002467
Anders Carlsson09025312009-08-29 05:16:22 +00002468 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002469 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002470 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002471 TemplateArgs,
2472 Init->getSourceLocation(),
2473 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002474 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002475 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002476 New->setInvalidDecl();
2477 continue;
2478 }
2479
John McCalla93c9342009-12-07 02:54:59 +00002480 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002481 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002482 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002483 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002484 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002485 New->getParent(),
2486 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002487 } else if (Init->isMemberInitializer()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002488 FieldDecl *Member = cast<FieldDecl>(FindInstantiatedDecl(
2489 Init->getMemberLocation(),
2490 Init->getMember(),
2491 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002492
2493 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002494 NewArgs.size(),
2495 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002496 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002497 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002498 } else if (Init->isIndirectMemberInitializer()) {
2499 IndirectFieldDecl *IndirectMember =
2500 cast<IndirectFieldDecl>(FindInstantiatedDecl(
2501 Init->getMemberLocation(),
2502 Init->getIndirectMember(), TemplateArgs));
2503
2504 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2505 NewArgs.size(),
2506 Init->getSourceLocation(),
2507 Init->getLParenLoc(),
2508 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002509 }
2510
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002511 if (NewInit.isInvalid()) {
2512 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002513 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002514 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002515 // FIXME: It would be nice if ASTOwningVector had a release function.
2516 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002517
Anders Carlsson09025312009-08-29 05:16:22 +00002518 NewInits.push_back((MemInitTy *)NewInit.get());
2519 }
2520 }
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Anders Carlsson09025312009-08-29 05:16:22 +00002522 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002523 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002524 /*FIXME: ColonLoc */
2525 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002526 NewInits.data(), NewInits.size(),
2527 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002528}
2529
John McCall52a575a2009-08-29 08:11:13 +00002530// TODO: this could be templated if the various decl types used the
2531// same method name.
2532static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2533 ClassTemplateDecl *Instance) {
2534 Pattern = Pattern->getCanonicalDecl();
2535
2536 do {
2537 Instance = Instance->getCanonicalDecl();
2538 if (Pattern == Instance) return true;
2539 Instance = Instance->getInstantiatedFromMemberTemplate();
2540 } while (Instance);
2541
2542 return false;
2543}
2544
Douglas Gregor0d696532009-09-28 06:34:35 +00002545static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2546 FunctionTemplateDecl *Instance) {
2547 Pattern = Pattern->getCanonicalDecl();
2548
2549 do {
2550 Instance = Instance->getCanonicalDecl();
2551 if (Pattern == Instance) return true;
2552 Instance = Instance->getInstantiatedFromMemberTemplate();
2553 } while (Instance);
2554
2555 return false;
2556}
2557
Douglas Gregored9c0f92009-10-29 00:04:11 +00002558static bool
2559isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2560 ClassTemplatePartialSpecializationDecl *Instance) {
2561 Pattern
2562 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2563 do {
2564 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2565 Instance->getCanonicalDecl());
2566 if (Pattern == Instance)
2567 return true;
2568 Instance = Instance->getInstantiatedFromMember();
2569 } while (Instance);
2570
2571 return false;
2572}
2573
John McCall52a575a2009-08-29 08:11:13 +00002574static bool isInstantiationOf(CXXRecordDecl *Pattern,
2575 CXXRecordDecl *Instance) {
2576 Pattern = Pattern->getCanonicalDecl();
2577
2578 do {
2579 Instance = Instance->getCanonicalDecl();
2580 if (Pattern == Instance) return true;
2581 Instance = Instance->getInstantiatedFromMemberClass();
2582 } while (Instance);
2583
2584 return false;
2585}
2586
2587static bool isInstantiationOf(FunctionDecl *Pattern,
2588 FunctionDecl *Instance) {
2589 Pattern = Pattern->getCanonicalDecl();
2590
2591 do {
2592 Instance = Instance->getCanonicalDecl();
2593 if (Pattern == Instance) return true;
2594 Instance = Instance->getInstantiatedFromMemberFunction();
2595 } while (Instance);
2596
2597 return false;
2598}
2599
2600static bool isInstantiationOf(EnumDecl *Pattern,
2601 EnumDecl *Instance) {
2602 Pattern = Pattern->getCanonicalDecl();
2603
2604 do {
2605 Instance = Instance->getCanonicalDecl();
2606 if (Pattern == Instance) return true;
2607 Instance = Instance->getInstantiatedFromMemberEnum();
2608 } while (Instance);
2609
2610 return false;
2611}
2612
John McCalled976492009-12-04 22:46:56 +00002613static bool isInstantiationOf(UsingShadowDecl *Pattern,
2614 UsingShadowDecl *Instance,
2615 ASTContext &C) {
2616 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2617}
2618
2619static bool isInstantiationOf(UsingDecl *Pattern,
2620 UsingDecl *Instance,
2621 ASTContext &C) {
2622 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2623}
2624
John McCall7ba107a2009-11-18 02:36:19 +00002625static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2626 UsingDecl *Instance,
2627 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002628 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002629}
2630
2631static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002632 UsingDecl *Instance,
2633 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002634 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002635}
2636
John McCall52a575a2009-08-29 08:11:13 +00002637static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2638 VarDecl *Instance) {
2639 assert(Instance->isStaticDataMember());
2640
2641 Pattern = Pattern->getCanonicalDecl();
2642
2643 do {
2644 Instance = Instance->getCanonicalDecl();
2645 if (Pattern == Instance) return true;
2646 Instance = Instance->getInstantiatedFromStaticDataMember();
2647 } while (Instance);
2648
2649 return false;
2650}
2651
John McCalled976492009-12-04 22:46:56 +00002652// Other is the prospective instantiation
2653// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002654static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002655 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002656 if (UnresolvedUsingTypenameDecl *UUD
2657 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2658 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2659 return isInstantiationOf(UUD, UD, Ctx);
2660 }
2661 }
2662
2663 if (UnresolvedUsingValueDecl *UUD
2664 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002665 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2666 return isInstantiationOf(UUD, UD, Ctx);
2667 }
2668 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002669
Anders Carlsson0d8df782009-08-29 19:37:28 +00002670 return false;
2671 }
Mike Stump1eb44332009-09-09 15:08:12 +00002672
John McCall52a575a2009-08-29 08:11:13 +00002673 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2674 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002675
John McCall52a575a2009-08-29 08:11:13 +00002676 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2677 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002678
John McCall52a575a2009-08-29 08:11:13 +00002679 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2680 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002681
Douglas Gregor7caa6822009-07-24 20:34:43 +00002682 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002683 if (Var->isStaticDataMember())
2684 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2685
2686 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2687 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002688
Douglas Gregor0d696532009-09-28 06:34:35 +00002689 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2690 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2691
Douglas Gregored9c0f92009-10-29 00:04:11 +00002692 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2693 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2694 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2695 PartialSpec);
2696
Anders Carlssond8b285f2009-09-01 04:26:58 +00002697 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2698 if (!Field->getDeclName()) {
2699 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002700 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002701 cast<FieldDecl>(D);
2702 }
2703 }
Mike Stump1eb44332009-09-09 15:08:12 +00002704
John McCalled976492009-12-04 22:46:56 +00002705 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2706 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2707
2708 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2709 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2710
Douglas Gregor815215d2009-05-27 05:35:12 +00002711 return D->getDeclName() && isa<NamedDecl>(Other) &&
2712 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2713}
2714
2715template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002716static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002717 NamedDecl *D,
2718 ForwardIterator first,
2719 ForwardIterator last) {
2720 for (; first != last; ++first)
2721 if (isInstantiationOf(Ctx, D, *first))
2722 return cast<NamedDecl>(*first);
2723
2724 return 0;
2725}
2726
John McCall02cace72009-08-28 07:59:38 +00002727/// \brief Finds the instantiation of the given declaration context
2728/// within the current instantiation.
2729///
2730/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002731DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002732 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002733 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002734 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002735 return cast_or_null<DeclContext>(ID);
2736 } else return DC;
2737}
2738
Douglas Gregored961e72009-05-27 17:54:46 +00002739/// \brief Find the instantiation of the given declaration within the
2740/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002741///
2742/// This routine is intended to be used when \p D is a declaration
2743/// referenced from within a template, that needs to mapped into the
2744/// corresponding declaration within an instantiation. For example,
2745/// given:
2746///
2747/// \code
2748/// template<typename T>
2749/// struct X {
2750/// enum Kind {
2751/// KnownValue = sizeof(T)
2752/// };
2753///
2754/// bool getKind() const { return KnownValue; }
2755/// };
2756///
2757/// template struct X<int>;
2758/// \endcode
2759///
2760/// In the instantiation of X<int>::getKind(), we need to map the
2761/// EnumConstantDecl for KnownValue (which refers to
2762/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002763/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2764/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002765NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002766 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002767 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002768 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002769 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002770 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002771 // D is a local of some kind. Look into the map of local
2772 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002773 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002774 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002775
Douglas Gregore95b4092009-09-16 18:34:49 +00002776 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2777 if (!Record->isDependentContext())
2778 return D;
2779
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002780 // If the RecordDecl is actually the injected-class-name or a
2781 // "templated" declaration for a class template, class template
2782 // partial specialization, or a member class of a class template,
2783 // substitute into the injected-class-name of the class template
2784 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002785 QualType T;
2786 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2787
2788 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002789 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002790 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2791 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002792 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002793
2794 // If we call SubstType with an InjectedClassNameType here we
2795 // can end up in an infinite loop.
2796 T = Context.getTypeDeclType(Record);
2797 assert(isa<InjectedClassNameType>(T) &&
2798 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002799 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002800 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002801
2802 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002803 // Substitute into the injected-class-name to get the type
2804 // corresponding to the instantiation we want, which may also be
2805 // the current instantiation (if we're in a template
2806 // definition). This substitution should never fail, since we
2807 // know we can instantiate the injected-class-name or we
2808 // wouldn't have gotten to the injected-class-name!
2809
2810 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2811 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002812 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2813 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2814
2815 if (!T->isDependentType()) {
2816 assert(T->isRecordType() && "Instantiation must produce a record type");
2817 return T->getAs<RecordType>()->getDecl();
2818 }
2819
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002820 // We are performing "partial" template instantiation to create
2821 // the member declarations for the members of a class template
2822 // specialization. Therefore, D is actually referring to something
2823 // in the current instantiation. Look through the current
2824 // context, which contains actual instantiations, to find the
2825 // instantiation of the "current instantiation" that D refers
2826 // to.
2827 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002828 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002829 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002830 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002831 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002832 if (isInstantiationOf(ClassTemplate,
2833 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002834 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002835
2836 if (!DC->isDependentContext())
2837 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002838 }
2839
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002840 // We're performing "instantiation" of a member of the current
2841 // instantiation while we are type-checking the
2842 // definition. Compute the declaration context and return that.
2843 assert(!SawNonDependentContext &&
2844 "No dependent context while instantiating record");
2845 DeclContext *DC = computeDeclContext(T);
2846 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002847 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002848 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002849 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002850
Douglas Gregore95b4092009-09-16 18:34:49 +00002851 // Fall through to deal with other dependent record types (e.g.,
2852 // anonymous unions in class templates).
2853 }
John McCall52a575a2009-08-29 08:11:13 +00002854
Douglas Gregore95b4092009-09-16 18:34:49 +00002855 if (!ParentDC->isDependentContext())
2856 return D;
2857
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002858 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002859 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002860 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002861
Douglas Gregor815215d2009-05-27 05:35:12 +00002862 if (ParentDC != D->getDeclContext()) {
2863 // We performed some kind of instantiation in the parent context,
2864 // so now we need to look into the instantiated parent context to
2865 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002866
John McCall3cb0ebd2010-03-10 03:28:59 +00002867 // If our context used to be dependent, we may need to instantiate
2868 // it before performing lookup into that context.
2869 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002870 if (!Spec->isDependentContext()) {
2871 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002872 const RecordType *Tag = T->getAs<RecordType>();
2873 assert(Tag && "type of non-dependent record is not a RecordType");
2874 if (!Tag->isBeingDefined() &&
2875 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2876 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00002877
2878 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002879 }
2880 }
2881
Douglas Gregor815215d2009-05-27 05:35:12 +00002882 NamedDecl *Result = 0;
2883 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002884 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002885 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2886 } else {
2887 // Since we don't have a name for the entity we're looking for,
2888 // our only option is to walk through all of the declarations to
2889 // find that name. This will occur in a few cases:
2890 //
2891 // - anonymous struct/union within a template
2892 // - unnamed class/struct/union/enum within a template
2893 //
2894 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002895 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002896 ParentDC->decls_begin(),
2897 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002898 }
Mike Stump1eb44332009-09-09 15:08:12 +00002899
John McCall9f54ad42009-12-10 09:41:52 +00002900 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002901 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2902 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002903 && "Unable to find instantiation of declaration!");
2904
Douglas Gregor815215d2009-05-27 05:35:12 +00002905 D = Result;
2906 }
2907
Douglas Gregor815215d2009-05-27 05:35:12 +00002908 return D;
2909}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002910
Mike Stump1eb44332009-09-09 15:08:12 +00002911/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002912/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002913void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002914 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00002915 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002916 PendingImplicitInstantiation Inst;
2917
2918 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002919 Inst = PendingInstantiations.front();
2920 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00002921 } else {
2922 Inst = PendingLocalImplicitInstantiations.front();
2923 PendingLocalImplicitInstantiations.pop_front();
2924 }
Mike Stump1eb44332009-09-09 15:08:12 +00002925
Douglas Gregor7caa6822009-07-24 20:34:43 +00002926 // Instantiate function definitions
2927 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00002928 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
2929 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00002930 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
2931 TSK_ExplicitInstantiationDefinition;
2932 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
2933 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002934 continue;
2935 }
Mike Stump1eb44332009-09-09 15:08:12 +00002936
Douglas Gregor7caa6822009-07-24 20:34:43 +00002937 // Instantiate static data member definitions.
2938 VarDecl *Var = cast<VarDecl>(Inst.first);
2939 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002940
Chandler Carruth291b4412010-02-13 10:17:50 +00002941 // Don't try to instantiate declarations if the most recent redeclaration
2942 // is invalid.
2943 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2944 continue;
2945
2946 // Check if the most recent declaration has changed the specialization kind
2947 // and removed the need for implicit instantiation.
2948 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2949 case TSK_Undeclared:
2950 assert(false && "Cannot instantitiate an undeclared specialization.");
2951 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00002952 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00002953 continue; // No longer need to instantiate this type.
2954 case TSK_ExplicitInstantiationDefinition:
2955 // We only need an instantiation if the pending instantiation *is* the
2956 // explicit instantiation.
2957 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00002958 case TSK_ImplicitInstantiation:
2959 break;
2960 }
2961
John McCallf312b1e2010-08-26 23:41:50 +00002962 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
2963 "instantiating static data member "
2964 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Chandler Carruth58e390e2010-08-25 08:27:02 +00002966 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
2967 TSK_ExplicitInstantiationDefinition;
2968 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
2969 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002970 }
2971}
John McCall0c01d182010-03-24 05:22:00 +00002972
2973void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2974 const MultiLevelTemplateArgumentList &TemplateArgs) {
2975 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2976 E = Pattern->ddiag_end(); I != E; ++I) {
2977 DependentDiagnostic *DD = *I;
2978
2979 switch (DD->getKind()) {
2980 case DependentDiagnostic::Access:
2981 HandleDependentAccessCheck(*DD, TemplateArgs);
2982 break;
2983 }
2984 }
2985}