blob: 1f0bd4cac21015aaf6bc9c1df003439fed5e4d41 [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) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000030 if (!OldDecl->getQualifierLoc())
31 return false;
32
33 NestedNameSpecifierLoc NewQualifierLoc
34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
35 TemplateArgs);
36
37 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000038 return true;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000039
40 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000041 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000046 if (!OldDecl->getQualifierLoc())
47 return false;
48
49 NestedNameSpecifierLoc NewQualifierLoc
50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51 TemplateArgs);
52
53 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000054 return true;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000055
56 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000057 return false;
58}
59
Chandler Carruth4ced79f2010-06-25 03:22:07 +000060// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +000061void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
62 Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +000063 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
64 i != e; ++i) {
65 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +000066 // FIXME: This should be generalized to more than just the AlignedAttr.
67 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +000068 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +000069 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +000070 EnterExpressionEvaluationContext Unevaluated(*this,
John McCallf312b1e2010-08-26 23:41:50 +000071 Sema::Unevaluated);
Chandler Carruth4ced79f2010-06-25 03:22:07 +000072
Sean Huntcf807c42010-08-18 23:23:40 +000073 if (Aligned->isAlignmentExpr()) {
John McCall60d7b3a2010-08-24 06:29:42 +000074 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Nick Lewycky7663f392010-11-20 01:29:55 +000075 TemplateArgs);
Sean Huntcf807c42010-08-18 23:23:40 +000076 if (!Result.isInvalid())
77 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
78 }
79 else {
80 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
Nick Lewycky7663f392010-11-20 01:29:55 +000081 TemplateArgs,
82 Aligned->getLocation(),
83 DeclarationName());
Sean Huntcf807c42010-08-18 23:23:40 +000084 if (Result)
85 AddAlignedAttr(Aligned->getLocation(), New, Result);
86 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +000087 continue;
88 }
89 }
90
Anders Carlssond8fe2d52009-11-07 06:07:58 +000091 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +000092 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +000093 New->addAttr(NewAttr);
94 }
95}
96
Douglas Gregor4f722be2009-03-25 15:45:12 +000097Decl *
98TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
99 assert(false && "Translation units cannot be instantiated");
100 return D;
101}
102
103Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000104TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
105 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
106 D->getIdentifier());
107 Owner->addDecl(Inst);
108 return Inst;
109}
110
111Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000112TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
113 assert(false && "Namespaces cannot be instantiated");
114 return D;
115}
116
John McCall3dbd3d52010-02-16 06:53:13 +0000117Decl *
118TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
119 NamespaceAliasDecl *Inst
120 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
121 D->getNamespaceLoc(),
122 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000123 D->getIdentifier(),
124 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000125 D->getTargetNameLoc(),
126 D->getNamespace());
127 Owner->addDecl(Inst);
128 return Inst;
129}
130
Richard Smith3e4c6c42011-05-05 21:57:07 +0000131Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
132 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000133 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000134 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000135 if (DI->getType()->isDependentType() ||
136 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000137 DI = SemaRef.SubstType(DI, TemplateArgs,
138 D->getLocation(), D->getDeclName());
139 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000140 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000141 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000143 } else {
144 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 }
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000148 TypedefNameDecl *Typedef;
149 if (IsTypeAlias)
150 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
151 D->getLocation(), D->getIdentifier(), DI);
152 else
153 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
154 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000155 if (Invalid)
156 Typedef->setInvalidDecl();
157
John McCallcde5a402011-02-01 08:20:08 +0000158 // If the old typedef was the name for linkage purposes of an anonymous
159 // tag decl, re-establish that relationship for the new typedef.
160 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
161 TagDecl *oldTag = oldTagType->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000162 if (oldTag->getTypedefNameForAnonDecl() == D) {
John McCallcde5a402011-02-01 08:20:08 +0000163 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000164 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
165 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000166 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000167 }
168
Richard Smith162e1c12011-04-15 14:24:37 +0000169 if (TypedefNameDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000170 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
171 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000172 if (!InstPrev)
173 return 0;
174
Richard Smith162e1c12011-04-15 14:24:37 +0000175 Typedef->setPreviousDeclaration(cast<TypedefNameDecl>(InstPrev));
John McCall5126fd02009-12-30 00:31:22 +0000176 }
177
John McCall1d8d1cc2010-08-01 02:01:53 +0000178 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000179
John McCall46460a62010-01-20 21:53:11 +0000180 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000182 return Typedef;
183}
184
Richard Smith162e1c12011-04-15 14:24:37 +0000185Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000186 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
187 Owner->addDecl(Typedef);
188 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000189}
190
191Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000192 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
193 Owner->addDecl(Typedef);
194 return Typedef;
195}
196
197Decl *
198TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
199 // Create a local instantiation scope for this type alias template, which
200 // will contain the instantiations of the template parameters.
201 LocalInstantiationScope Scope(SemaRef);
202
203 TemplateParameterList *TempParams = D->getTemplateParameters();
204 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
205 if (!InstParams)
206 return 0;
207
208 TypeAliasDecl *Pattern = D->getTemplatedDecl();
209
210 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
211 if (Pattern->getPreviousDeclaration()) {
212 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
213 if (Found.first != Found.second) {
214 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
215 }
216 }
217
218 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
219 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
220 if (!AliasInst)
221 return 0;
222
223 TypeAliasTemplateDecl *Inst
224 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
225 D->getDeclName(), InstParams, AliasInst);
226 if (PrevAliasTemplate)
227 Inst->setPreviousDeclaration(PrevAliasTemplate);
228
229 Inst->setAccess(D->getAccess());
230
231 if (!PrevAliasTemplate)
232 Inst->setInstantiatedFromMemberTemplate(D);
233
234 Owner->addDecl(Inst);
235
236 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000237}
238
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000239/// \brief Instantiate an initializer, breaking it into separate
240/// initialization arguments.
241///
242/// \param S The semantic analysis object.
243///
244/// \param Init The initializer to instantiate.
245///
246/// \param TemplateArgs Template arguments to be substituted into the
247/// initializer.
248///
249/// \param NewArgs Will be filled in with the instantiation arguments.
250///
251/// \returns true if an error occurred, false otherwise
252static bool InstantiateInitializer(Sema &S, Expr *Init,
253 const MultiLevelTemplateArgumentList &TemplateArgs,
254 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000255 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000256 SourceLocation &RParenLoc) {
257 NewArgs.clear();
258 LParenLoc = SourceLocation();
259 RParenLoc = SourceLocation();
260
261 if (!Init)
262 return false;
263
John McCall4765fa02010-12-06 08:20:24 +0000264 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000265 Init = ExprTemp->getSubExpr();
266
267 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
268 Init = Binder->getSubExpr();
269
270 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
271 Init = ICE->getSubExprAsWritten();
272
273 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
274 LParenLoc = ParenList->getLParenLoc();
275 RParenLoc = ParenList->getRParenLoc();
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000276 return S.SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
277 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000278 }
279
280 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000281 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000282 if (S.SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
283 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000284 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000285
Douglas Gregor28329e52010-03-24 21:22:47 +0000286 // FIXME: Fake locations!
287 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000288 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000289 return false;
290 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000291 }
292
John McCall60d7b3a2010-08-24 06:29:42 +0000293 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000294 if (Result.isInvalid())
295 return true;
296
297 NewArgs.push_back(Result.takeAs<Expr>());
298 return false;
299}
300
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000301Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000302 // If this is the variable for an anonymous struct or union,
303 // instantiate the anonymous struct/union type first.
304 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
305 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
306 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
307 return 0;
308
John McCallce3ff2b2009-08-25 22:02:44 +0000309 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000310 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000311 TemplateArgs,
312 D->getTypeSpecStartLoc(),
313 D->getDeclName());
314 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000315 return 0;
316
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000317 if (DI->getType()->isFunctionType()) {
318 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
319 << D->isStaticDataMember() << DI->getType();
320 return 0;
321 }
322
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000323 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000324 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000325 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000326 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000327 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000328 D->getStorageClass(),
329 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000330 Var->setThreadSpecified(D->isThreadSpecified());
331 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Richard Smithad762fc2011-04-14 22:09:26 +0000332 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCallb6217662010-03-15 10:12:16 +0000334 // Substitute the nested name specifier, if any.
335 if (SubstQualifier(D, Var))
336 return 0;
337
Mike Stump1eb44332009-09-09 15:08:12 +0000338 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000339 // out-of-line, the instantiation will have the same lexical
340 // context (which will be a namespace scope) as the template.
341 if (D->isOutOfLine())
342 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000343
John McCall46460a62010-01-20 21:53:11 +0000344 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000345
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000346 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000347 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000348 Var->setReferenced(D->isReferenced());
349 }
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000350
Mike Stump390b4cc2009-05-16 07:39:55 +0000351 // FIXME: In theory, we could have a previous declaration for variables that
352 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000353 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000354 // FIXME: having to fake up a LookupResult is dumb.
355 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000356 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000357 if (D->isStaticDataMember())
358 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000359 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregor7caa6822009-07-24 20:34:43 +0000361 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000362 if (!D->isStaticDataMember())
363 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000364 Owner->makeDeclVisibleInContext(Var);
365 } else {
366 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000367 if (Owner->isFunctionOrMethod())
368 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000369 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000370 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000371
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000372 // Link instantiations of static data members back to the template from
373 // which they were instantiated.
374 if (Var->isStaticDataMember())
375 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000376 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000377
Douglas Gregor60c93c92010-02-09 07:26:29 +0000378 if (Var->getAnyInitializer()) {
379 // We already have an initializer in the class.
380 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000381 if (Var->isStaticDataMember() && !D->isOutOfLine())
382 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
383 else
384 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
385
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000386 // Instantiate the initializer.
387 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000388 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000389 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000390 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000391 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000392 // Attach the initializer to the declaration, if we have one.
393 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000394 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000395 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000396 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000397 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000398 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000399 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000400 RParenLoc,
401 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000402 } else {
403 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000404 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000405 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000406 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000407 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000408 // FIXME: Not too happy about invalidating the declaration
409 // because of a bogus initializer.
410 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000411 }
412
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000413 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000414 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
415 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000416 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000417
Douglas Gregor5764f612010-05-08 23:05:03 +0000418 // Diagnose unused local variables.
419 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
420 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000421
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000422 return Var;
423}
424
Abramo Bagnara6206d532010-06-05 05:09:32 +0000425Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
426 AccessSpecDecl* AD
427 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
428 D->getAccessSpecifierLoc(), D->getColonLoc());
429 Owner->addHiddenDecl(AD);
430 return AD;
431}
432
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000433Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
434 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000435 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000436 if (DI->getType()->isDependentType() ||
437 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000438 DI = SemaRef.SubstType(DI, TemplateArgs,
439 D->getLocation(), D->getDeclName());
440 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000441 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000442 Invalid = true;
443 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000444 // C++ [temp.arg.type]p3:
445 // If a declaration acquires a function type through a type
446 // dependent on a template-parameter and this causes a
447 // declaration that does not use the syntactic form of a
448 // function declarator to have function type, the program is
449 // ill-formed.
450 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000451 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000452 Invalid = true;
453 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000454 } else {
455 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000456 }
457
458 Expr *BitWidth = D->getBitWidth();
459 if (Invalid)
460 BitWidth = 0;
461 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000462 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000463 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
John McCall60d7b3a2010-08-24 06:29:42 +0000465 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000466 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000467 if (InstantiatedBitWidth.isInvalid()) {
468 Invalid = true;
469 BitWidth = 0;
470 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000471 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000472 }
473
John McCall07fb6be2009-10-22 23:33:21 +0000474 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
475 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000476 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000477 D->getLocation(),
478 D->isMutable(),
479 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000480 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000481 D->getAccess(),
482 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000483 if (!Field) {
484 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000485 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
John McCall1d8d1cc2010-08-01 02:01:53 +0000488 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000489
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000490 if (Invalid)
491 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000493 if (!Field->getDeclName()) {
494 // Keep track of where this decl came from.
495 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000496 }
497 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
498 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000499 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000500 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000503 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000504 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000505 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000506
507 return Field;
508}
509
Francois Pichet87c2e122010-11-21 06:08:52 +0000510Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
511 NamedDecl **NamedChain =
512 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
513
514 int i = 0;
515 for (IndirectFieldDecl::chain_iterator PI =
516 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000517 PI != PE; ++PI) {
518 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
519 TemplateArgs);
520 if (!Next)
521 return 0;
522
523 NamedChain[i++] = Next;
524 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000525
Francois Pichet40e17752010-12-09 10:07:54 +0000526 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000527 IndirectFieldDecl* IndirectField
528 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000529 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000530 NamedChain, D->getChainingSize());
531
532
533 IndirectField->setImplicit(D->isImplicit());
534 IndirectField->setAccess(D->getAccess());
535 Owner->addDecl(IndirectField);
536 return IndirectField;
537}
538
John McCall02cace72009-08-28 07:59:38 +0000539Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000540 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000541 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000542 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000543 TypeSourceInfo *InstTy;
544 // If this is an unsupported friend, don't bother substituting template
545 // arguments into it. The actual type referred to won't be used by any
546 // parts of Clang, and may not be valid for instantiating. Just use the
547 // same info for the instantiated friend.
548 if (D->isUnsupportedFriend()) {
549 InstTy = Ty;
550 } else {
551 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
552 D->getLocation(), DeclarationName());
553 }
554 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000555 return 0;
John McCall02cace72009-08-28 07:59:38 +0000556
Douglas Gregor06245bf2010-04-07 17:57:12 +0000557 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
558 if (!FD)
559 return 0;
560
561 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000562 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000563 Owner->addDecl(FD);
564 return FD;
565 }
566
567 NamedDecl *ND = D->getFriendDecl();
568 assert(ND && "friend decl must be a decl or a type!");
569
John McCallaf2094e2010-04-08 09:05:18 +0000570 // All of the Visit implementations for the various potential friend
571 // declarations have to be carefully written to work for friend
572 // objects, with the most important detail being that the target
573 // decl should almost certainly not be placed in Owner.
574 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000575 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCall02cace72009-08-28 07:59:38 +0000577 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000578 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
579 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000580 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000581 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000582 Owner->addDecl(FD);
583 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000584}
585
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000586Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
587 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Douglas Gregorac7610d2009-06-22 20:57:11 +0000589 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000590 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000591
John McCall60d7b3a2010-08-24 06:29:42 +0000592 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000593 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000594 if (InstantiatedAssertExpr.isInvalid())
595 return 0;
596
John McCall60d7b3a2010-08-24 06:29:42 +0000597 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000598 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000599 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000600 InstantiatedAssertExpr.get(),
Abramo Bagnaraa2026c92011-03-08 16:41:52 +0000601 Message.get(),
602 D->getRParenLoc());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000603}
604
605Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000606 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000607 D->getLocation(), D->getIdentifier(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000608 /*PrevDecl=*/0, D->isScoped(),
609 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000610 if (D->isFixed()) {
611 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
612 // If we have type source information for the underlying type, it means it
613 // has been explicitly set by the user. Perform substitution on it before
614 // moving on.
615 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
616 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
617 TemplateArgs,
618 UnderlyingLoc,
619 DeclarationName()));
620
621 if (!Enum->getIntegerTypeSourceInfo())
622 Enum->setIntegerType(SemaRef.Context.IntTy);
623 }
624 else {
625 assert(!D->getIntegerType()->isDependentType()
626 && "Dependent type without type source info");
627 Enum->setIntegerType(D->getIntegerType());
628 }
629 }
630
John McCall5b629aa2010-10-22 23:36:17 +0000631 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
632
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000633 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000634 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000635 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000636 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000637 Enum->startDefinition();
638
Douglas Gregor96084f12010-03-01 19:00:07 +0000639 if (D->getDeclContext()->isFunctionOrMethod())
640 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
641
John McCalld226f652010-08-21 09:40:31 +0000642 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000643
644 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000645 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
646 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000647 EC != ECEnd; ++EC) {
648 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000649 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000650 if (Expr *UninstValue = EC->getInitExpr()) {
651 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000652 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000653 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000654
John McCallce3ff2b2009-08-25 22:02:44 +0000655 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000656 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000657
658 // Drop the initial value and continue.
659 bool isInvalid = false;
660 if (Value.isInvalid()) {
661 Value = SemaRef.Owned((Expr *)0);
662 isInvalid = true;
663 }
664
Mike Stump1eb44332009-09-09 15:08:12 +0000665 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000666 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
667 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000668 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000669
670 if (isInvalid) {
671 if (EnumConst)
672 EnumConst->setInvalidDecl();
673 Enum->setInvalidDecl();
674 }
675
676 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000677 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
678
John McCall3b85ecf2010-01-23 22:37:59 +0000679 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000680 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000681 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000682 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000683
684 if (D->getDeclContext()->isFunctionOrMethod()) {
685 // If the enumeration is within a function or method, record the enum
686 // constant as a local.
687 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
688 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000689 }
690 }
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000692 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000693 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000694 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000695 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000696 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000697 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000698
699 return Enum;
700}
701
Douglas Gregor6477b692009-03-25 15:04:13 +0000702Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
703 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
704 return 0;
705}
706
John McCalle29ba202009-08-20 01:44:21 +0000707Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000708 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
709
Douglas Gregor550d9b22009-10-31 17:21:17 +0000710 // Create a local instantiation scope for this class template, which
711 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000712 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000713 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000714 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000715 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000716 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000717
718 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000719
720 // Instantiate the qualifier. We have to do this first in case
721 // we're a friend declaration, because if we are then we need to put
722 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000723 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
724 if (QualifierLoc) {
725 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
726 TemplateArgs);
727 if (!QualifierLoc)
728 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000729 }
730
731 CXXRecordDecl *PrevDecl = 0;
732 ClassTemplateDecl *PrevClassTemplate = 0;
733
Nick Lewycky37574f52010-11-08 23:29:42 +0000734 if (!isFriend && Pattern->getPreviousDeclaration()) {
735 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
736 if (Found.first != Found.second) {
737 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
738 if (PrevClassTemplate)
739 PrevDecl = PrevClassTemplate->getTemplatedDecl();
740 }
741 }
742
John McCall93ba8572010-03-25 06:39:04 +0000743 // If this isn't a friend, then it's a member template, in which
744 // case we just want to build the instantiation in the
745 // specialization. If it is a friend, we want to build it in
746 // the appropriate context.
747 DeclContext *DC = Owner;
748 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000749 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000750 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000751 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000752 DC = SemaRef.computeDeclContext(SS);
753 if (!DC) return 0;
754 } else {
755 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
756 Pattern->getDeclContext(),
757 TemplateArgs);
758 }
759
760 // Look for a previous declaration of the template in the owning
761 // context.
762 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
763 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
764 SemaRef.LookupQualifiedName(R, DC);
765
766 if (R.isSingleResult()) {
767 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
768 if (PrevClassTemplate)
769 PrevDecl = PrevClassTemplate->getTemplatedDecl();
770 }
771
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000772 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000773 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000774 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000775 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000776 return 0;
777 }
778
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000779 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000780 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000781 bool Complain = true;
782
783 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
784 // template for struct std::tr1::__detail::_Map_base, where the
785 // template parameters of the friend declaration don't match the
786 // template parameters of the original declaration. In this one
787 // case, we don't complain about the ill-formed friend
788 // declaration.
789 if (isFriend && Pattern->getIdentifier() &&
790 Pattern->getIdentifier()->isStr("_Map_base") &&
791 DC->isNamespace() &&
792 cast<NamespaceDecl>(DC)->getIdentifier() &&
793 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
794 DeclContext *DCParent = DC->getParent();
795 if (DCParent->isNamespace() &&
796 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
797 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
798 DeclContext *DCParent2 = DCParent->getParent();
799 if (DCParent2->isNamespace() &&
800 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
801 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
802 DCParent2->getParent()->isTranslationUnit())
803 Complain = false;
804 }
805 }
806
John McCall93ba8572010-03-25 06:39:04 +0000807 TemplateParameterList *PrevParams
808 = PrevClassTemplate->getTemplateParameters();
809
810 // Make sure the parameter lists match.
811 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000812 Complain,
813 Sema::TPL_TemplateMatch)) {
814 if (Complain)
815 return 0;
816
817 AdoptedPreviousTemplateParams = true;
818 InstParams = PrevParams;
819 }
John McCall93ba8572010-03-25 06:39:04 +0000820
821 // Do some additional validation, then merge default arguments
822 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000823 if (!AdoptedPreviousTemplateParams &&
824 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000825 Sema::TPC_ClassTemplate))
826 return 0;
827 }
828 }
829
John McCalle29ba202009-08-20 01:44:21 +0000830 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000831 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000832 Pattern->getLocStart(), Pattern->getLocation(),
833 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000834 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000835
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000836 if (QualifierLoc)
837 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000838
John McCalle29ba202009-08-20 01:44:21 +0000839 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000840 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
841 D->getIdentifier(), InstParams, RecordInst,
842 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000843 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000844
John McCall93ba8572010-03-25 06:39:04 +0000845 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000846 if (PrevClassTemplate)
847 Inst->setAccess(PrevClassTemplate->getAccess());
848 else
849 Inst->setAccess(D->getAccess());
850
John McCall93ba8572010-03-25 06:39:04 +0000851 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
852 // TODO: do we want to track the instantiation progeny of this
853 // friend target decl?
854 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000855 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000856 if (!PrevClassTemplate)
857 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000858 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000859
860 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000861 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000862 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000863
Douglas Gregor259571e2009-10-30 22:42:42 +0000864 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000865 if (isFriend) {
866 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000867 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000868 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000869
John McCalle29ba202009-08-20 01:44:21 +0000870 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000871
872 if (!PrevClassTemplate) {
873 // Queue up any out-of-line partial specializations of this member
874 // class template; the client will force their instantiation once
875 // the enclosing class has been instantiated.
876 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
877 D->getPartialSpecializations(PartialSpecs);
878 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
879 if (PartialSpecs[I]->isOutOfLine())
880 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
881 }
882
John McCalle29ba202009-08-20 01:44:21 +0000883 return Inst;
884}
885
Douglas Gregord60e1052009-08-27 16:57:43 +0000886Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000887TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
888 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000889 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
890
891 // Lookup the already-instantiated declaration in the instantiation
892 // of the class template and return that.
893 DeclContext::lookup_result Found
894 = Owner->lookup(ClassTemplate->getDeclName());
895 if (Found.first == Found.second)
896 return 0;
897
898 ClassTemplateDecl *InstClassTemplate
899 = dyn_cast<ClassTemplateDecl>(*Found.first);
900 if (!InstClassTemplate)
901 return 0;
902
Douglas Gregord65587f2010-11-10 19:44:59 +0000903 if (ClassTemplatePartialSpecializationDecl *Result
904 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
905 return Result;
906
907 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000908}
909
910Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000911TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000912 // Create a local instantiation scope for this function template, which
913 // will contain the instantiations of the template parameters and then get
914 // merged with the local instantiation scope for the function template
915 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000916 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000917
Douglas Gregord60e1052009-08-27 16:57:43 +0000918 TemplateParameterList *TempParams = D->getTemplateParameters();
919 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000920 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000921 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000922
Douglas Gregora735b202009-10-13 14:39:41 +0000923 FunctionDecl *Instantiated = 0;
924 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
925 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
926 InstParams));
927 else
928 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
929 D->getTemplatedDecl(),
930 InstParams));
931
932 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000933 return 0;
934
John McCall46460a62010-01-20 21:53:11 +0000935 Instantiated->setAccess(D->getAccess());
936
Mike Stump1eb44332009-09-09 15:08:12 +0000937 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000938 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000939 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000940 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000941 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000942 assert(InstTemplate &&
943 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000944
John McCallb1a56e72010-03-26 23:10:15 +0000945 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
946
John McCalle976ffe2009-12-14 23:19:40 +0000947 // Link the instantiation back to the pattern *unless* this is a
948 // non-definition friend declaration.
949 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000950 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000951 InstTemplate->setInstantiatedFromMemberTemplate(D);
952
John McCallb1a56e72010-03-26 23:10:15 +0000953 // Make declarations visible in the appropriate context.
954 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000955 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000956
Douglas Gregord60e1052009-08-27 16:57:43 +0000957 return InstTemplate;
958}
959
Douglas Gregord475b8d2009-03-25 21:17:03 +0000960Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
961 CXXRecordDecl *PrevDecl = 0;
962 if (D->isInjectedClassName())
963 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000964 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000965 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
966 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000967 TemplateArgs);
968 if (!Prev) return 0;
969 PrevDecl = cast<CXXRecordDecl>(Prev);
970 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000971
972 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000973 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000974 D->getLocStart(), D->getLocation(),
975 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000976
977 // Substitute the nested name specifier, if any.
978 if (SubstQualifier(D, Record))
979 return 0;
980
Douglas Gregord475b8d2009-03-25 21:17:03 +0000981 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000982 // FIXME: Check against AS_none is an ugly hack to work around the issue that
983 // the tag decls introduced by friend class declarations don't have an access
984 // specifier. Remove once this area of the code gets sorted out.
985 if (D->getAccess() != AS_none)
986 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000987 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000988 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000989
John McCall02cace72009-08-28 07:59:38 +0000990 // If the original function was part of a friend declaration,
991 // inherit its namespace state.
992 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
993 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
994
Douglas Gregor9901c572010-05-21 00:31:19 +0000995 // Make sure that anonymous structs and unions are recorded.
996 if (D->isAnonymousStructOrUnion()) {
997 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000998 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000999 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1000 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001001
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001002 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001003 return Record;
1004}
1005
John McCall02cace72009-08-28 07:59:38 +00001006/// Normal class members are of more specific types and therefore
1007/// don't make it here. This function serves two purposes:
1008/// 1) instantiating function templates
1009/// 2) substituting friend declarations
1010/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001011Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001012 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001013 // Check whether there is already a function template specialization for
1014 // this declaration.
1015 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1016 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +00001017 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +00001018 std::pair<const TemplateArgument *, unsigned> Innermost
1019 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001021 FunctionDecl *SpecFunc
1022 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1023 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Douglas Gregor127102b2009-06-29 20:59:39 +00001025 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001026 if (SpecFunc)
1027 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
John McCallb0cb0222010-03-27 05:57:59 +00001030 bool isFriend;
1031 if (FunctionTemplate)
1032 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1033 else
1034 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1035
Douglas Gregor79c22782010-01-16 20:21:20 +00001036 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001037 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +00001038 !(isa<Decl>(Owner) &&
1039 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001040 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Douglas Gregore53060f2009-06-25 22:08:12 +00001042 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001043 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1044 TInfo = SubstFunctionType(D, Params);
1045 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001046 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001047 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001048
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001049 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1050 if (QualifierLoc) {
1051 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1052 TemplateArgs);
1053 if (!QualifierLoc)
1054 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001055 }
1056
John McCall68b6b872010-02-06 01:50:47 +00001057 // If we're instantiating a local function declaration, put the result
1058 // in the owner; otherwise we need to find the instantiated context.
1059 DeclContext *DC;
1060 if (D->getDeclContext()->isFunctionOrMethod())
1061 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001062 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001063 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001064 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001065 DC = SemaRef.computeDeclContext(SS);
1066 if (!DC) return 0;
1067 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001068 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1069 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001070 }
John McCall68b6b872010-02-06 01:50:47 +00001071
John McCall02cace72009-08-28 07:59:38 +00001072 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001073 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1074 D->getLocation(), D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001075 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001076 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001077
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001078 if (QualifierLoc)
1079 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001080
John McCallb1a56e72010-03-26 23:10:15 +00001081 DeclContext *LexicalDC = Owner;
1082 if (!isFriend && D->isOutOfLine()) {
1083 assert(D->getDeclContext()->isFileContext());
1084 LexicalDC = D->getDeclContext();
1085 }
1086
1087 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Douglas Gregore53060f2009-06-25 22:08:12 +00001089 // Attach the parameters
1090 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001091 if (Params[P])
1092 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001093 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001094
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001095 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001096 if (TemplateParams) {
1097 // Our resulting instantiation is actually a function template, since we
1098 // are substituting only the outer template parameters. For example, given
1099 //
1100 // template<typename T>
1101 // struct X {
1102 // template<typename U> friend void f(T, U);
1103 // };
1104 //
1105 // X<int> x;
1106 //
1107 // We are instantiating the friend function template "f" within X<int>,
1108 // which means substituting int for T, but leaving "f" as a friend function
1109 // template.
1110 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001111 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001112 Function->getLocation(),
1113 Function->getDeclName(),
1114 TemplateParams, Function);
1115 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001116
1117 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001118
1119 if (isFriend && D->isThisDeclarationADefinition()) {
1120 // TODO: should we remember this connection regardless of whether
1121 // the friend declaration provided a body?
1122 FunctionTemplate->setInstantiatedFromMemberTemplate(
1123 D->getDescribedFunctionTemplate());
1124 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001125 } else if (FunctionTemplate) {
1126 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001127 std::pair<const TemplateArgument *, unsigned> Innermost
1128 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001129 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001130 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001131 Innermost.first,
1132 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001133 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001134 } else if (isFriend && D->isThisDeclarationADefinition()) {
1135 // TODO: should we remember this connection regardless of whether
1136 // the friend declaration provided a body?
1137 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001138 }
Douglas Gregora735b202009-10-13 14:39:41 +00001139
Douglas Gregore53060f2009-06-25 22:08:12 +00001140 if (InitFunctionInstantiation(Function, D))
1141 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Douglas Gregore53060f2009-06-25 22:08:12 +00001143 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001144 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001145
John McCall68263142009-11-18 22:49:29 +00001146 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1147 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1148
John McCallaf2094e2010-04-08 09:05:18 +00001149 if (DependentFunctionTemplateSpecializationInfo *Info
1150 = D->getDependentSpecializationInfo()) {
1151 assert(isFriend && "non-friend has dependent specialization info?");
1152
1153 // This needs to be set now for future sanity.
1154 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1155
1156 // Instantiate the explicit template arguments.
1157 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1158 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001159 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1160 ExplicitArgs, TemplateArgs))
1161 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001162
1163 // Map the candidate templates to their instantiations.
1164 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1165 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1166 Info->getTemplate(I),
1167 TemplateArgs);
1168 if (!Temp) return 0;
1169
1170 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1171 }
1172
1173 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1174 &ExplicitArgs,
1175 Previous))
1176 Function->setInvalidDecl();
1177
1178 isExplicitSpecialization = true;
1179
1180 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001181 // Look only into the namespace where the friend would be declared to
1182 // find a previous declaration. This is the innermost enclosing namespace,
1183 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001184 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001185
Douglas Gregora735b202009-10-13 14:39:41 +00001186 // In C++, the previous declaration we find might be a tag type
1187 // (class or enum). In this case, the new declaration will hide the
1188 // tag type. Note that this does does not apply if we're declaring a
1189 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001190 if (Previous.isSingleTagDecl())
1191 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001192 }
1193
John McCall9f54ad42009-12-10 09:41:52 +00001194 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001195 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001196
John McCall76d32642010-04-24 01:30:58 +00001197 NamedDecl *PrincipalDecl = (TemplateParams
1198 ? cast<NamedDecl>(FunctionTemplate)
1199 : Function);
1200
Douglas Gregora735b202009-10-13 14:39:41 +00001201 // If the original function was part of a friend declaration,
1202 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001203 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001204 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001205 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001206 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001207 else
Douglas Gregora735b202009-10-13 14:39:41 +00001208 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001209
1210 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1211 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001212
Gabor Greif77535df2010-08-30 22:25:56 +00001213 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001214
Douglas Gregor238058c2010-05-18 05:45:02 +00001215 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1216 D->isThisDeclarationADefinition()) {
1217 // Check for a function body.
1218 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001219 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001220 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1221 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1222 << Function->getDeclName();
1223 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1224 Function->setInvalidDecl();
1225 }
1226 // Check for redefinitions due to other instantiations of this or
1227 // a similar friend function.
1228 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1229 REnd = Function->redecls_end();
1230 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001231 if (*R == Function)
1232 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001233 switch (R->getFriendObjectKind()) {
1234 case Decl::FOK_None:
1235 if (!queuedInstantiation && R->isUsed(false)) {
1236 if (MemberSpecializationInfo *MSInfo
1237 = Function->getMemberSpecializationInfo()) {
1238 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1239 SourceLocation Loc = R->getLocation(); // FIXME
1240 MSInfo->setPointOfInstantiation(Loc);
1241 SemaRef.PendingLocalImplicitInstantiations.push_back(
1242 std::make_pair(Function, Loc));
1243 queuedInstantiation = true;
1244 }
1245 }
1246 }
1247 break;
1248 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001249 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001250 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001251 if (RPattern->isDefined(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001252 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1253 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001254 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001255 Function->setInvalidDecl();
1256 break;
1257 }
1258 }
1259 }
1260 }
Douglas Gregora735b202009-10-13 14:39:41 +00001261 }
1262
John McCall76d32642010-04-24 01:30:58 +00001263 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1264 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1265 PrincipalDecl->setNonMemberOperator();
1266
Douglas Gregore53060f2009-06-25 22:08:12 +00001267 return Function;
1268}
1269
Douglas Gregord60e1052009-08-27 16:57:43 +00001270Decl *
1271TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1272 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001273 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1274 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001275 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001276 // We are creating a function template specialization from a function
1277 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001278 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001279 std::pair<const TemplateArgument *, unsigned> Innermost
1280 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001282 FunctionDecl *SpecFunc
1283 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1284 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Douglas Gregor6b906862009-08-21 00:16:32 +00001286 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001287 if (SpecFunc)
1288 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001289 }
1290
John McCallb0cb0222010-03-27 05:57:59 +00001291 bool isFriend;
1292 if (FunctionTemplate)
1293 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1294 else
1295 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1296
Douglas Gregor79c22782010-01-16 20:21:20 +00001297 bool MergeWithParentScope = (TemplateParams != 0) ||
1298 !(isa<Decl>(Owner) &&
1299 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001300 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001301
John McCall4eab39f2010-10-19 02:26:41 +00001302 // Instantiate enclosing template arguments for friends.
1303 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1304 unsigned NumTempParamLists = 0;
1305 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1306 TempParamLists.set_size(NumTempParamLists);
1307 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1308 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1309 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1310 if (!InstParams)
1311 return NULL;
1312 TempParamLists[I] = InstParams;
1313 }
1314 }
1315
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001316 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001317 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1318 TInfo = SubstFunctionType(D, Params);
1319 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001320 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001321 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001322
Abramo Bagnara723df242010-12-14 22:11:44 +00001323 // \brief If the type of this function, after ignoring parentheses,
1324 // is not *directly* a function type, then we're instantiating a function
1325 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001326 //
1327 // typedef int functype(int, int);
1328 // functype func;
1329 //
1330 // In this case, we'll just go instantiate the ParmVarDecls that we
1331 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001332 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001333 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001334 llvm::SmallVector<QualType, 4> ParamTypes;
1335 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1336 D->getNumParams(), TemplateArgs, ParamTypes,
1337 &Params))
1338 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001339 }
1340
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001341 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1342 if (QualifierLoc) {
1343 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001344 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001345 if (!QualifierLoc)
1346 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001347 }
1348
1349 DeclContext *DC = Owner;
1350 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001351 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001352 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001353 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001354 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001355
1356 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1357 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001358 } else {
1359 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1360 D->getDeclContext(),
1361 TemplateArgs);
1362 }
1363 if (!DC) return 0;
1364 }
1365
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001366 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001367 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001368 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001370 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001371 DeclarationNameInfo NameInfo
1372 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001373 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001374 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001375 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001376 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001377 Constructor->isInlineSpecified(),
Sean Hunt5f802e52011-05-06 00:11:07 +00001378 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001379 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001380 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001381 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001382 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001383 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001384 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001385 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001386 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001387 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001388 Conversion->isExplicit(),
1389 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001390 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001391 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001392 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001393 D->isStatic(),
1394 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001395 D->isInlineSpecified(),
1396 D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001397 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001398
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001399 if (QualifierLoc)
1400 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001401
Douglas Gregord60e1052009-08-27 16:57:43 +00001402 if (TemplateParams) {
1403 // Our resulting instantiation is actually a function template, since we
1404 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001405 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001406 // template<typename T>
1407 // struct X {
1408 // template<typename U> void f(T, U);
1409 // };
1410 //
1411 // X<int> x;
1412 //
1413 // We are instantiating the member template "f" within X<int>, which means
1414 // substituting int for T, but leaving "f" as a member function template.
1415 // Build the function template itself.
1416 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1417 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001418 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001419 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001420 if (isFriend) {
1421 FunctionTemplate->setLexicalDeclContext(Owner);
1422 FunctionTemplate->setObjectOfFriendDecl(true);
1423 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001424 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001425 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001426 } else if (FunctionTemplate) {
1427 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001428 std::pair<const TemplateArgument *, unsigned> Innermost
1429 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001430 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001431 TemplateArgumentList::CreateCopy(SemaRef.Context,
1432 Innermost.first,
1433 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001434 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001435 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001436 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001437 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001438 }
1439
Mike Stump1eb44332009-09-09 15:08:12 +00001440 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001441 // out-of-line, the instantiation will have the same lexical
1442 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001443 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001444 if (NumTempParamLists)
1445 Method->setTemplateParameterListsInfo(SemaRef.Context,
1446 NumTempParamLists,
1447 TempParamLists.data());
1448
John McCallb0cb0222010-03-27 05:57:59 +00001449 Method->setLexicalDeclContext(Owner);
1450 Method->setObjectOfFriendDecl(true);
1451 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001452 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Douglas Gregor5545e162009-03-24 00:38:23 +00001454 // Attach the parameters
1455 for (unsigned P = 0; P < Params.size(); ++P)
1456 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001457 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001458
1459 if (InitMethodInstantiation(Method, D))
1460 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001461
Abramo Bagnara25777432010-08-11 22:01:17 +00001462 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1463 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001464
John McCallb0cb0222010-03-27 05:57:59 +00001465 if (!FunctionTemplate || TemplateParams || isFriend) {
1466 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Douglas Gregordec06662009-08-21 18:42:58 +00001468 // In C++, the previous declaration we find might be a tag type
1469 // (class or enum). In this case, the new declaration will hide the
1470 // tag type. Note that this does does not apply if we're declaring a
1471 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001472 if (Previous.isSingleTagDecl())
1473 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001474 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001475
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001476 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001477 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001478
Douglas Gregor4ba31362009-12-01 17:24:26 +00001479 if (D->isPure())
1480 SemaRef.CheckPureMethod(Method, SourceRange());
1481
John McCall46460a62010-01-20 21:53:11 +00001482 Method->setAccess(D->getAccess());
1483
Anders Carlsson9eefa222011-01-20 06:52:44 +00001484 SemaRef.CheckOverrideControl(Method);
1485
John McCallb0cb0222010-03-27 05:57:59 +00001486 if (FunctionTemplate) {
1487 // If there's a function template, let our caller handle it.
1488 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1489 // Don't hide a (potentially) valid declaration with an invalid one.
1490 } else {
1491 NamedDecl *DeclToAdd = (TemplateParams
1492 ? cast<NamedDecl>(FunctionTemplate)
1493 : Method);
1494 if (isFriend)
1495 Record->makeDeclVisibleInContext(DeclToAdd);
1496 else
1497 Owner->addDecl(DeclToAdd);
1498 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001499
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001500 return Method;
1501}
1502
Douglas Gregor615c5d42009-03-24 16:43:20 +00001503Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001504 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001505}
1506
Douglas Gregor03b2b072009-03-24 00:15:49 +00001507Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001508 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001509}
1510
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001511Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001512 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001513}
1514
Douglas Gregor6477b692009-03-25 15:04:13 +00001515ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallfb44de92011-05-01 22:35:37 +00001516 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1517 llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001518}
1519
John McCalle29ba202009-08-20 01:44:21 +00001520Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1521 TemplateTypeParmDecl *D) {
1522 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001523 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001524
John McCalle29ba202009-08-20 01:44:21 +00001525 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001526 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1527 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001528 D->getDepth() - TemplateArgs.getNumLevels(),
1529 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001530 D->wasDeclaredWithTypename(),
1531 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001532 Inst->setAccess(AS_public);
1533
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001534 if (D->hasDefaultArgument())
1535 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001536
Douglas Gregor550d9b22009-10-31 17:21:17 +00001537 // Introduce this template parameter's instantiation into the instantiation
1538 // scope.
1539 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1540
John McCalle29ba202009-08-20 01:44:21 +00001541 return Inst;
1542}
1543
Douglas Gregor33642df2009-10-23 23:25:44 +00001544Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1545 NonTypeTemplateParmDecl *D) {
1546 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001547 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1548 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1549 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1550 bool IsExpandedParameterPack = false;
1551 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001552 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001553 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001554
1555 if (D->isExpandedParameterPack()) {
1556 // The non-type template parameter pack is an already-expanded pack
1557 // expansion of types. Substitute into each of the expanded types.
1558 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1559 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1560 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1561 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1562 TemplateArgs,
1563 D->getLocation(),
1564 D->getDeclName());
1565 if (!NewDI)
1566 return 0;
1567
1568 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1569 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1570 D->getLocation());
1571 if (NewT.isNull())
1572 return 0;
1573 ExpandedParameterPackTypes.push_back(NewT);
1574 }
1575
1576 IsExpandedParameterPack = true;
1577 DI = D->getTypeSourceInfo();
1578 T = DI->getType();
1579 } else if (isa<PackExpansionTypeLoc>(TL)) {
1580 // The non-type template parameter pack's type is a pack expansion of types.
1581 // Determine whether we need to expand this parameter pack into separate
1582 // types.
1583 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1584 TypeLoc Pattern = Expansion.getPatternLoc();
1585 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1586 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1587
1588 // Determine whether the set of unexpanded parameter packs can and should
1589 // be expanded.
1590 bool Expand = true;
1591 bool RetainExpansion = false;
1592 llvm::Optional<unsigned> OrigNumExpansions
1593 = Expansion.getTypePtr()->getNumExpansions();
1594 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1595 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1596 Pattern.getSourceRange(),
1597 Unexpanded.data(),
1598 Unexpanded.size(),
1599 TemplateArgs,
1600 Expand, RetainExpansion,
1601 NumExpansions))
1602 return 0;
1603
1604 if (Expand) {
1605 for (unsigned I = 0; I != *NumExpansions; ++I) {
1606 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1607 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1608 D->getLocation(),
1609 D->getDeclName());
1610 if (!NewDI)
1611 return 0;
1612
1613 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1614 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1615 NewDI->getType(),
1616 D->getLocation());
1617 if (NewT.isNull())
1618 return 0;
1619 ExpandedParameterPackTypes.push_back(NewT);
1620 }
1621
1622 // Note that we have an expanded parameter pack. The "type" of this
1623 // expanded parameter pack is the original expansion type, but callers
1624 // will end up using the expanded parameter pack types for type-checking.
1625 IsExpandedParameterPack = true;
1626 DI = D->getTypeSourceInfo();
1627 T = DI->getType();
1628 } else {
1629 // We cannot fully expand the pack expansion now, so substitute into the
1630 // pattern and create a new pack expansion type.
1631 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1632 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1633 D->getLocation(),
1634 D->getDeclName());
1635 if (!NewPattern)
1636 return 0;
1637
1638 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1639 NumExpansions);
1640 if (!DI)
1641 return 0;
1642
1643 T = DI->getType();
1644 }
1645 } else {
1646 // Simple case: substitution into a parameter that is not a parameter pack.
1647 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1648 D->getLocation(), D->getDeclName());
1649 if (!DI)
1650 return 0;
1651
1652 // Check that this type is acceptable for a non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001653 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1654 D->getLocation());
1655 if (T.isNull()) {
1656 T = SemaRef.Context.IntTy;
1657 Invalid = true;
1658 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001659 }
1660
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001661 NonTypeTemplateParmDecl *Param;
1662 if (IsExpandedParameterPack)
1663 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001664 D->getInnerLocStart(),
1665 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001666 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001667 D->getPosition(),
1668 D->getIdentifier(), T,
1669 DI,
1670 ExpandedParameterPackTypes.data(),
1671 ExpandedParameterPackTypes.size(),
1672 ExpandedParameterPackTypesAsWritten.data());
1673 else
1674 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001675 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001676 D->getLocation(),
1677 D->getDepth() - TemplateArgs.getNumLevels(),
1678 D->getPosition(),
1679 D->getIdentifier(), T,
1680 D->isParameterPack(), DI);
1681
Douglas Gregor9a299e02011-03-04 17:52:15 +00001682 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001683 if (Invalid)
1684 Param->setInvalidDecl();
1685
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001686 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001687
1688 // Introduce this template parameter's instantiation into the instantiation
1689 // scope.
1690 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001691 return Param;
1692}
1693
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001694Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001695TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1696 TemplateTemplateParmDecl *D) {
1697 // Instantiate the template parameter list of the template template parameter.
1698 TemplateParameterList *TempParams = D->getTemplateParameters();
1699 TemplateParameterList *InstParams;
1700 {
1701 // Perform the actual substitution of template parameters within a new,
1702 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001703 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001704 InstParams = SubstTemplateParams(TempParams);
1705 if (!InstParams)
1706 return NULL;
1707 }
1708
1709 // Build the template template parameter.
1710 TemplateTemplateParmDecl *Param
1711 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001712 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001713 D->getPosition(), D->isParameterPack(),
1714 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001715 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001716 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001717
Douglas Gregor9106ef72009-11-11 16:58:32 +00001718 // Introduce this template parameter's instantiation into the instantiation
1719 // scope.
1720 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1721
1722 return Param;
1723}
1724
Douglas Gregor48c32a72009-11-17 06:07:40 +00001725Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001726 // Using directives are never dependent (and never contain any types or
1727 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001728
1729 UsingDirectiveDecl *Inst
1730 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1731 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001732 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001733 D->getIdentLocation(),
1734 D->getNominatedNamespace(),
1735 D->getCommonAncestor());
1736 Owner->addDecl(Inst);
1737 return Inst;
1738}
1739
John McCalled976492009-12-04 22:46:56 +00001740Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001741
1742 // The nested name specifier may be dependent, for example
1743 // template <typename T> struct t {
1744 // struct s1 { T f1(); };
1745 // struct s2 : s1 { using s1::f1; };
1746 // };
1747 // template struct t<int>;
1748 // Here, in using s1::f1, s1 refers to t<T>::s1;
1749 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001750 NestedNameSpecifierLoc QualifierLoc
1751 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1752 TemplateArgs);
1753 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001754 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001755
1756 // The name info is non-dependent, so no transformation
1757 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001758 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001759
John McCall9f54ad42009-12-10 09:41:52 +00001760 // We only need to do redeclaration lookups if we're in a class
1761 // scope (in fact, it's not really even possible in non-class
1762 // scopes).
1763 bool CheckRedeclaration = Owner->isRecord();
1764
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001765 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1766 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001767
John McCalled976492009-12-04 22:46:56 +00001768 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001769 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001770 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001771 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001772 D->isTypeName());
1773
Douglas Gregor5149f372011-02-25 15:54:31 +00001774 CXXScopeSpec SS;
1775 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001776 if (CheckRedeclaration) {
1777 Prev.setHideTags(false);
1778 SemaRef.LookupQualifiedName(Prev, Owner);
1779
1780 // Check for invalid redeclarations.
1781 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1782 D->isTypeName(), SS,
1783 D->getLocation(), Prev))
1784 NewUD->setInvalidDecl();
1785
1786 }
1787
1788 if (!NewUD->isInvalidDecl() &&
1789 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001790 D->getLocation()))
1791 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001792
John McCalled976492009-12-04 22:46:56 +00001793 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1794 NewUD->setAccess(D->getAccess());
1795 Owner->addDecl(NewUD);
1796
John McCall9f54ad42009-12-10 09:41:52 +00001797 // Don't process the shadow decls for an invalid decl.
1798 if (NewUD->isInvalidDecl())
1799 return NewUD;
1800
John McCall323c3102009-12-22 22:26:37 +00001801 bool isFunctionScope = Owner->isFunctionOrMethod();
1802
John McCall9f54ad42009-12-10 09:41:52 +00001803 // Process the shadow decls.
1804 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1805 I != E; ++I) {
1806 UsingShadowDecl *Shadow = *I;
1807 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001808 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1809 Shadow->getLocation(),
1810 Shadow->getTargetDecl(),
1811 TemplateArgs));
1812 if (!InstTarget)
1813 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001814
1815 if (CheckRedeclaration &&
1816 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1817 continue;
1818
1819 UsingShadowDecl *InstShadow
1820 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1821 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001822
1823 if (isFunctionScope)
1824 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001825 }
John McCalled976492009-12-04 22:46:56 +00001826
1827 return NewUD;
1828}
1829
1830Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001831 // Ignore these; we handle them in bulk when processing the UsingDecl.
1832 return 0;
John McCalled976492009-12-04 22:46:56 +00001833}
1834
John McCall7ba107a2009-11-18 02:36:19 +00001835Decl * TemplateDeclInstantiator
1836 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001837 NestedNameSpecifierLoc QualifierLoc
1838 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1839 TemplateArgs);
1840 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001841 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001843 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001844 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001846 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1847 // Hence, no tranformation is required for it.
1848 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001849 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001850 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001851 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001852 /*instantiation*/ true,
1853 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001854 if (UD)
John McCalled976492009-12-04 22:46:56 +00001855 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1856
John McCall7ba107a2009-11-18 02:36:19 +00001857 return UD;
1858}
1859
1860Decl * TemplateDeclInstantiator
1861 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001862 NestedNameSpecifierLoc QualifierLoc
1863 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1864 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001865 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001866
John McCall7ba107a2009-11-18 02:36:19 +00001867 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001868 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001869
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001870 DeclarationNameInfo NameInfo
1871 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1872
John McCall7ba107a2009-11-18 02:36:19 +00001873 NamedDecl *UD =
1874 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001875 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001876 /*instantiation*/ true,
1877 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001878 if (UD)
John McCalled976492009-12-04 22:46:56 +00001879 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1880
Anders Carlsson0d8df782009-08-29 19:37:28 +00001881 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001882}
1883
John McCallce3ff2b2009-08-25 22:02:44 +00001884Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001885 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001886 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001887 if (D->isInvalidDecl())
1888 return 0;
1889
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001890 return Instantiator.Visit(D);
1891}
1892
John McCalle29ba202009-08-20 01:44:21 +00001893/// \brief Instantiates a nested template parameter list in the current
1894/// instantiation context.
1895///
1896/// \param L The parameter list to instantiate
1897///
1898/// \returns NULL if there was an error
1899TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001900TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001901 // Get errors for all the parameters before bailing out.
1902 bool Invalid = false;
1903
1904 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001905 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001906 ParamVector Params;
1907 Params.reserve(N);
1908 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1909 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001910 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001911 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001912 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001913 }
1914
1915 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001916 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001917 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001918
1919 TemplateParameterList *InstL
1920 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1921 L->getLAngleLoc(), &Params.front(), N,
1922 L->getRAngleLoc());
1923 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001924}
John McCalle29ba202009-08-20 01:44:21 +00001925
Douglas Gregored9c0f92009-10-29 00:04:11 +00001926/// \brief Instantiate the declaration of a class template partial
1927/// specialization.
1928///
1929/// \param ClassTemplate the (instantiated) class template that is partially
1930// specialized by the instantiation of \p PartialSpec.
1931///
1932/// \param PartialSpec the (uninstantiated) class template partial
1933/// specialization that we are instantiating.
1934///
Douglas Gregord65587f2010-11-10 19:44:59 +00001935/// \returns The instantiated partial specialization, if successful; otherwise,
1936/// NULL to indicate an error.
1937ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001938TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1939 ClassTemplateDecl *ClassTemplate,
1940 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001941 // Create a local instantiation scope for this class template partial
1942 // specialization, which will contain the instantiations of the template
1943 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001944 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001945
Douglas Gregored9c0f92009-10-29 00:04:11 +00001946 // Substitute into the template parameters of the class template partial
1947 // specialization.
1948 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1949 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1950 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001951 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001952
1953 // Substitute into the template arguments of the class template partial
1954 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001955 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001956 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1957 PartialSpec->getNumTemplateArgsAsWritten(),
1958 InstTemplateArgs, TemplateArgs))
1959 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001960
Douglas Gregored9c0f92009-10-29 00:04:11 +00001961 // Check that the template argument list is well-formed for this
1962 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001963 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001964 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1965 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001966 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001967 false,
1968 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001969 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001970
1971 // Figure out where to insert this class template partial specialization
1972 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001973 void *InsertPos = 0;
1974 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001975 = ClassTemplate->findPartialSpecialization(Converted.data(),
1976 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001977
1978 // Build the canonical type that describes the converted template
1979 // arguments of the class template partial specialization.
1980 QualType CanonType
1981 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001982 Converted.data(),
1983 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001984
1985 // Build the fully-sugared type for this class template
1986 // specialization as the user wrote in the specialization
1987 // itself. This means that we'll pretty-print the type retrieved
1988 // from the specialization's declaration the way that the user
1989 // actually wrote the specialization, rather than formatting the
1990 // name based on the "canonical" representation used to store the
1991 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001992 TypeSourceInfo *WrittenTy
1993 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1994 TemplateName(ClassTemplate),
1995 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001996 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001997 CanonType);
1998
1999 if (PrevDecl) {
2000 // We've already seen a partial specialization with the same template
2001 // parameters and template arguments. This can happen, for example, when
2002 // substituting the outer template arguments ends up causing two
2003 // class template partial specializations of a member class template
2004 // to have identical forms, e.g.,
2005 //
2006 // template<typename T, typename U>
2007 // struct Outer {
2008 // template<typename X, typename Y> struct Inner;
2009 // template<typename Y> struct Inner<T, Y>;
2010 // template<typename Y> struct Inner<U, Y>;
2011 // };
2012 //
2013 // Outer<int, int> outer; // error: the partial specializations of Inner
2014 // // have the same signature.
2015 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002016 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002017 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2018 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002019 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002020 }
2021
2022
2023 // Create the class template partial specialization declaration.
2024 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00002025 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2026 PartialSpec->getTagKind(),
2027 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002028 PartialSpec->getLocStart(),
2029 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002030 InstParams,
2031 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002032 Converted.data(),
2033 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002034 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002035 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002036 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002037 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002038 // Substitute the nested name specifier, if any.
2039 if (SubstQualifier(PartialSpec, InstPartialSpec))
2040 return 0;
2041
Douglas Gregored9c0f92009-10-29 00:04:11 +00002042 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002043 InstPartialSpec->setTypeAsWritten(WrittenTy);
2044
Douglas Gregored9c0f92009-10-29 00:04:11 +00002045 // Add this partial specialization to the set of class template partial
2046 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002047 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00002048 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002049}
2050
John McCall21ef0fa2010-03-11 09:03:00 +00002051TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002052TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00002053 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002054 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2055 assert(OldTInfo && "substituting function without type source info");
2056 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00002057 TypeSourceInfo *NewTInfo
2058 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2059 D->getTypeSpecStartLoc(),
2060 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00002061 if (!NewTInfo)
2062 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002063
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002064 if (NewTInfo != OldTInfo) {
2065 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002066 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002067 if (FunctionProtoTypeLoc *OldProtoLoc
2068 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002069 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002070 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2071 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002072 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2073 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2074 OldIdx != NumOldParams; ++OldIdx) {
2075 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2076 if (!OldParam->isParameterPack() ||
2077 (NewIdx < NumNewParams &&
2078 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2079 // Simple case: normal parameter, or a parameter pack that's
2080 // instantiated to a (still-dependent) parameter pack.
2081 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2082 Params.push_back(NewParam);
2083 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2084 NewParam);
2085 continue;
2086 }
2087
2088 // Parameter pack: make the instantiation an argument pack.
2089 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2090 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002091 unsigned NumArgumentsInExpansion
2092 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2093 TemplateArgs);
2094 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002095 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2096 Params.push_back(NewParam);
2097 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2098 NewParam);
2099 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002100 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002101 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002102 } else {
2103 // The function type itself was not dependent and therefore no
2104 // substitution occurred. However, we still need to instantiate
2105 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002106 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002107 if (FunctionProtoTypeLoc *OldProtoLoc
2108 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2109 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2110 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2111 if (!Parm)
2112 return 0;
2113 Params.push_back(Parm);
2114 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002115 }
2116 }
John McCall21ef0fa2010-03-11 09:03:00 +00002117 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002118}
2119
Mike Stump1eb44332009-09-09 15:08:12 +00002120/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002121/// declaration (New) from the corresponding fields of its template (Tmpl).
2122///
2123/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002124bool
2125TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002126 FunctionDecl *Tmpl) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002127 if (Tmpl->isDeletedAsWritten())
2128 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Douglas Gregorcca9e962009-07-01 22:01:06 +00002130 // If we are performing substituting explicitly-specified template arguments
2131 // or deduced template arguments into a function template and we reach this
2132 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002133 // to keeping the new function template specialization. We therefore
2134 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002135 // into a template instantiation for this specific function template
2136 // specialization, which is not a SFINAE context, so that we diagnose any
2137 // further errors in the declaration itself.
2138 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2139 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2140 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2141 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002142 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002143 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002144 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002145 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002146 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002147 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2148 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002149 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002150 }
2151 }
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002153 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2154 assert(Proto && "Function template without prototype?");
2155
Sebastian Redl60618fa2011-03-12 11:50:43 +00002156 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002157 // The function has an exception specification or a "noreturn"
2158 // attribute. Substitute into each of the exception types.
2159 llvm::SmallVector<QualType, 4> Exceptions;
2160 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2161 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002162 if (const PackExpansionType *PackExpansion
2163 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2164 // We have a pack expansion. Instantiate it.
2165 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2166 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2167 Unexpanded);
2168 assert(!Unexpanded.empty() &&
2169 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002170
Douglas Gregorb99268b2010-12-21 00:52:54 +00002171 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002172 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002173 llvm::Optional<unsigned> NumExpansions
2174 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002175 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2176 SourceRange(),
2177 Unexpanded.data(),
2178 Unexpanded.size(),
2179 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002180 Expand,
2181 RetainExpansion,
2182 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002183 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002184
Douglas Gregorb99268b2010-12-21 00:52:54 +00002185 if (!Expand) {
2186 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002187 // just substitute into the pattern and create a new pack expansion
2188 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002189 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2190 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2191 TemplateArgs,
2192 New->getLocation(), New->getDeclName());
2193 if (T.isNull())
2194 break;
2195
Douglas Gregorcded4f62011-01-14 17:04:44 +00002196 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002197 Exceptions.push_back(T);
2198 continue;
2199 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002200
Douglas Gregorb99268b2010-12-21 00:52:54 +00002201 // Substitute into the pack expansion pattern for each template
2202 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002203 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002204 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2205
2206 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2207 TemplateArgs,
2208 New->getLocation(), New->getDeclName());
2209 if (T.isNull()) {
2210 Invalid = true;
2211 break;
2212 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002213
Douglas Gregorb99268b2010-12-21 00:52:54 +00002214 Exceptions.push_back(T);
2215 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002216
Douglas Gregorb99268b2010-12-21 00:52:54 +00002217 if (Invalid)
2218 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002219
Douglas Gregorb99268b2010-12-21 00:52:54 +00002220 continue;
2221 }
2222
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002223 QualType T
2224 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2225 New->getLocation(), New->getDeclName());
2226 if (T.isNull() ||
2227 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2228 continue;
2229
2230 Exceptions.push_back(T);
2231 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002232 Expr *NoexceptExpr = 0;
2233 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2234 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2235 if (E.isUsable())
2236 NoexceptExpr = E.take();
2237 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002238
2239 // Rebuild the function type
2240
John McCalle23cf432010-12-14 08:05:40 +00002241 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002242 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002243 EPI.NumExceptions = Exceptions.size();
2244 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002245 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002246 EPI.ExtInfo = Proto->getExtInfo();
2247
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002248 const FunctionProtoType *NewProto
2249 = New->getType()->getAs<FunctionProtoType>();
2250 assert(NewProto && "Template instantiation without function prototype?");
2251 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2252 NewProto->arg_type_begin(),
2253 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002254 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002255 }
2256
John McCall1d8d1cc2010-08-01 02:01:53 +00002257 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002258
Douglas Gregore53060f2009-06-25 22:08:12 +00002259 return false;
2260}
2261
Douglas Gregor5545e162009-03-24 00:38:23 +00002262/// \brief Initializes common fields of an instantiated method
2263/// declaration (New) from the corresponding fields of its template
2264/// (Tmpl).
2265///
2266/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002267bool
2268TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002269 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002270 if (InitFunctionInstantiation(New, Tmpl))
2271 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Douglas Gregor5545e162009-03-24 00:38:23 +00002273 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002274 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002275 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002276
2277 // FIXME: attributes
2278 // FIXME: New needs a pointer to Tmpl
2279 return false;
2280}
Douglas Gregora58861f2009-05-13 20:28:22 +00002281
2282/// \brief Instantiate the definition of the given function from its
2283/// template.
2284///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002285/// \param PointOfInstantiation the point at which the instantiation was
2286/// required. Note that this is not precisely a "point of instantiation"
2287/// for the function, but it's close.
2288///
Douglas Gregora58861f2009-05-13 20:28:22 +00002289/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002290/// function template specialization or member function of a class template
2291/// specialization.
2292///
2293/// \param Recursive if true, recursively instantiates any functions that
2294/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002295///
2296/// \param DefinitionRequired if true, then we are performing an explicit
2297/// instantiation where the body of the function is required. Complain if
2298/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002299void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002300 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002301 bool Recursive,
2302 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002303 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002304 return;
2305
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002306 // Never instantiate an explicit specialization.
2307 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2308 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002309
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002310 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002311 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002312 Stmt *Pattern = 0;
2313 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002314 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002315
Francois Pichet8387e2a2011-04-22 22:18:13 +00002316 // Postpone late parsed template instantiations.
2317 if (PatternDecl->isLateTemplateParsed() && !LateTemplateParser) {
2318 PendingInstantiations.push_back(
2319 std::make_pair(Function, PointOfInstantiation));
2320 return;
2321 }
2322
2323 // Call the LateTemplateParser callback if there a need to late parse
2324 // a templated function definition.
2325 if (!Pattern && PatternDecl && PatternDecl->isLateTemplateParsed() &&
2326 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002327 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002328 Pattern = PatternDecl->getBody(PatternDecl);
2329 }
2330
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002331 if (!Pattern) {
2332 if (DefinitionRequired) {
2333 if (Function->getPrimaryTemplate())
2334 Diag(PointOfInstantiation,
2335 diag::err_explicit_instantiation_undefined_func_template)
2336 << Function->getPrimaryTemplate();
2337 else
2338 Diag(PointOfInstantiation,
2339 diag::err_explicit_instantiation_undefined_member)
2340 << 1 << Function->getDeclName() << Function->getDeclContext();
2341
2342 if (PatternDecl)
2343 Diag(PatternDecl->getLocation(),
2344 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002345 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002346 } else if (Function->getTemplateSpecializationKind()
2347 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002348 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002349 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002350 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002351
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002352 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002353 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002354
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002355 // C++0x [temp.explicit]p9:
2356 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002357 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002358 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002359 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002360 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002361 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002362 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002364 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2365 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002366 return;
2367
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002368 // If we're performing recursive template instantiation, create our own
2369 // queue of pending implicit instantiations that we will instantiate later,
2370 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002371 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002372 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002373 if (Recursive) {
2374 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002375 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002376 }
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Douglas Gregor9679caf2010-05-12 17:27:19 +00002378 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002379 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002380 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002381
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002382 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002383 // recorded, unless we're actually a member function within a local
2384 // class, in which case we need to merge our results with the parent
2385 // scope (of the enclosing function).
2386 bool MergeWithParentScope = false;
2387 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2388 MergeWithParentScope = Rec->isLocalClass();
2389
2390 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002392 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002393 // instantiation scope, and set the parameter names to those used
2394 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002395 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002396 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2397 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002398 if (!PatternParam->isParameterPack()) {
2399 // Simple case: not a parameter pack.
2400 assert(FParamIdx < Function->getNumParams());
2401 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2402 FunctionParam->setDeclName(PatternParam->getDeclName());
2403 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2404 ++FParamIdx;
2405 continue;
2406 }
2407
2408 // Expand the parameter pack.
2409 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2410 for (unsigned NumFParams = Function->getNumParams();
2411 FParamIdx < NumFParams;
2412 ++FParamIdx) {
2413 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2414 FunctionParam->setDeclName(PatternParam->getDeclName());
2415 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2416 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002417 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002418
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002419 // Enter the scope of this instantiation. We don't use
2420 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002421 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002422
Mike Stump1eb44332009-09-09 15:08:12 +00002423 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002424 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002425
2426 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002427 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002428 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2429 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2430 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002431 }
2432
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002433 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002434 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002435
Douglas Gregor52604ab2009-09-11 21:19:12 +00002436 if (Body.isInvalid())
2437 Function->setInvalidDecl();
2438
John McCall9ae2f072010-08-23 23:25:46 +00002439 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002440 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002441
John McCall0c01d182010-03-24 05:22:00 +00002442 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2443
John McCalleee1d542011-02-14 07:13:47 +00002444 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002445
2446 DeclGroupRef DG(Function);
2447 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Douglas Gregor60406be2010-01-16 22:29:39 +00002449 // This class may have local implicit instantiations that need to be
2450 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002451 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002452 Scope.Exit();
2453
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002454 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002455 // Define any pending vtables.
2456 DefineUsedVTables();
2457
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002458 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002459 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002460 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002462 // Restore the set of pending vtables.
2463 VTableUses.swap(SavedVTableUses);
2464
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002465 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002466 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002467 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002468}
2469
2470/// \brief Instantiate the definition of the given variable from its
2471/// template.
2472///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002473/// \param PointOfInstantiation the point at which the instantiation was
2474/// required. Note that this is not precisely a "point of instantiation"
2475/// for the function, but it's close.
2476///
2477/// \param Var the already-instantiated declaration of a static member
2478/// variable of a class template specialization.
2479///
2480/// \param Recursive if true, recursively instantiates any functions that
2481/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002482///
2483/// \param DefinitionRequired if true, then we are performing an explicit
2484/// instantiation where an out-of-line definition of the member variable
2485/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002486void Sema::InstantiateStaticDataMemberDefinition(
2487 SourceLocation PointOfInstantiation,
2488 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002489 bool Recursive,
2490 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002491 if (Var->isInvalidDecl())
2492 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Douglas Gregor7caa6822009-07-24 20:34:43 +00002494 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002495 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002496 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002497 assert(Def->isStaticDataMember() && "Not a static data member?");
2498 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002499
Douglas Gregor0d035142009-10-27 18:42:08 +00002500 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002501 // We did not find an out-of-line definition of this static data member,
2502 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002503 // instantiate this definition (or provide a specialization for it) in
2504 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002505 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002506 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002507 Diag(PointOfInstantiation,
2508 diag::err_explicit_instantiation_undefined_member)
2509 << 2 << Var->getDeclName() << Var->getDeclContext();
2510 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002511 } else if (Var->getTemplateSpecializationKind()
2512 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002513 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002514 std::make_pair(Var, PointOfInstantiation));
2515 }
2516
Douglas Gregor7caa6822009-07-24 20:34:43 +00002517 return;
2518 }
2519
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002520 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002521 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002522 return;
2523
2524 // C++0x [temp.explicit]p9:
2525 // Except for inline functions, other explicit instantiation declarations
2526 // have the effect of suppressing the implicit instantiation of the entity
2527 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002528 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002529 == TSK_ExplicitInstantiationDeclaration)
2530 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Douglas Gregor7caa6822009-07-24 20:34:43 +00002532 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2533 if (Inst)
2534 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Douglas Gregor7caa6822009-07-24 20:34:43 +00002536 // If we're performing recursive template instantiation, create our own
2537 // queue of pending implicit instantiations that we will instantiate later,
2538 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002539 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002540 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002541 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002542
Douglas Gregor7caa6822009-07-24 20:34:43 +00002543 // Enter the scope of this instantiation. We don't use
2544 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002545 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002547 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002548 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002549 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002550
2551 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002552
2553 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002554 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2555 assert(MSInfo && "Missing member specialization information?");
2556 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2557 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002558 DeclGroupRef DG(Var);
2559 Consumer.HandleTopLevelDecl(DG);
2560 }
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Douglas Gregor7caa6822009-07-24 20:34:43 +00002562 if (Recursive) {
2563 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002564 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002565 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002566
Douglas Gregor7caa6822009-07-24 20:34:43 +00002567 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002568 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002569 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002570}
Douglas Gregor815215d2009-05-27 05:35:12 +00002571
Anders Carlsson09025312009-08-29 05:16:22 +00002572void
2573Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2574 const CXXConstructorDecl *Tmpl,
2575 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Anders Carlsson09025312009-08-29 05:16:22 +00002577 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002578 bool AnyErrors = false;
2579
Anders Carlsson09025312009-08-29 05:16:22 +00002580 // Instantiate all the initializers.
2581 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002582 InitsEnd = Tmpl->init_end();
2583 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002584 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002585
Chandler Carruth030ef472010-09-03 21:54:20 +00002586 // Only instantiate written initializers, let Sema re-construct implicit
2587 // ones.
2588 if (!Init->isWritten())
2589 continue;
2590
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002591 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002592 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002594 SourceLocation EllipsisLoc;
2595
2596 if (Init->isPackExpansion()) {
2597 // This is a pack expansion. We should expand it now.
2598 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2599 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2600 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2601 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002602 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002603 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002604 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2605 BaseTL.getSourceRange(),
2606 Unexpanded.data(),
2607 Unexpanded.size(),
2608 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002609 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002610 NumExpansions)) {
2611 AnyErrors = true;
2612 New->setInvalidDecl();
2613 continue;
2614 }
2615 assert(ShouldExpand && "Partial instantiation of base initializer?");
2616
2617 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002618 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002619 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2620
2621 // Instantiate the initializer.
2622 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2623 LParenLoc, NewArgs, RParenLoc)) {
2624 AnyErrors = true;
2625 break;
2626 }
2627
2628 // Instantiate the base type.
2629 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2630 TemplateArgs,
2631 Init->getSourceLocation(),
2632 New->getDeclName());
2633 if (!BaseTInfo) {
2634 AnyErrors = true;
2635 break;
2636 }
2637
2638 // Build the initializer.
2639 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2640 BaseTInfo,
2641 (Expr **)NewArgs.data(),
2642 NewArgs.size(),
2643 Init->getLParenLoc(),
2644 Init->getRParenLoc(),
2645 New->getParent(),
2646 SourceLocation());
2647 if (NewInit.isInvalid()) {
2648 AnyErrors = true;
2649 break;
2650 }
2651
2652 NewInits.push_back(NewInit.get());
2653 NewArgs.clear();
2654 }
2655
2656 continue;
2657 }
2658
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002659 // Instantiate the initializer.
2660 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002661 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002662 AnyErrors = true;
2663 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002664 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002665
Anders Carlsson09025312009-08-29 05:16:22 +00002666 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002667 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002668 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002669 TemplateArgs,
2670 Init->getSourceLocation(),
2671 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002672 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002673 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002674 New->setInvalidDecl();
2675 continue;
2676 }
2677
John McCalla93c9342009-12-07 02:54:59 +00002678 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002679 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002680 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002681 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002682 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002683 New->getParent(),
2684 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002685 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002686 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002687 Init->getMemberLocation(),
2688 Init->getMember(),
2689 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002690 if (!Member) {
2691 AnyErrors = true;
2692 New->setInvalidDecl();
2693 continue;
2694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
2696 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002697 NewArgs.size(),
2698 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002699 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002700 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002701 } else if (Init->isIndirectMemberInitializer()) {
2702 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002703 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002704 Init->getMemberLocation(),
2705 Init->getIndirectMember(), TemplateArgs));
2706
Douglas Gregorb7107222011-03-04 19:46:35 +00002707 if (!IndirectMember) {
2708 AnyErrors = true;
2709 New->setInvalidDecl();
2710 continue;
2711 }
2712
Francois Pichet00eb3f92010-12-04 09:14:42 +00002713 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2714 NewArgs.size(),
2715 Init->getSourceLocation(),
2716 Init->getLParenLoc(),
2717 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002718 }
2719
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002720 if (NewInit.isInvalid()) {
2721 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002722 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002723 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002724 // FIXME: It would be nice if ASTOwningVector had a release function.
2725 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Anders Carlsson09025312009-08-29 05:16:22 +00002727 NewInits.push_back((MemInitTy *)NewInit.get());
2728 }
2729 }
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Anders Carlsson09025312009-08-29 05:16:22 +00002731 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002732 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002733 /*FIXME: ColonLoc */
2734 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002735 NewInits.data(), NewInits.size(),
2736 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002737}
2738
John McCall52a575a2009-08-29 08:11:13 +00002739// TODO: this could be templated if the various decl types used the
2740// same method name.
2741static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2742 ClassTemplateDecl *Instance) {
2743 Pattern = Pattern->getCanonicalDecl();
2744
2745 do {
2746 Instance = Instance->getCanonicalDecl();
2747 if (Pattern == Instance) return true;
2748 Instance = Instance->getInstantiatedFromMemberTemplate();
2749 } while (Instance);
2750
2751 return false;
2752}
2753
Douglas Gregor0d696532009-09-28 06:34:35 +00002754static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2755 FunctionTemplateDecl *Instance) {
2756 Pattern = Pattern->getCanonicalDecl();
2757
2758 do {
2759 Instance = Instance->getCanonicalDecl();
2760 if (Pattern == Instance) return true;
2761 Instance = Instance->getInstantiatedFromMemberTemplate();
2762 } while (Instance);
2763
2764 return false;
2765}
2766
Douglas Gregored9c0f92009-10-29 00:04:11 +00002767static bool
2768isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2769 ClassTemplatePartialSpecializationDecl *Instance) {
2770 Pattern
2771 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2772 do {
2773 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2774 Instance->getCanonicalDecl());
2775 if (Pattern == Instance)
2776 return true;
2777 Instance = Instance->getInstantiatedFromMember();
2778 } while (Instance);
2779
2780 return false;
2781}
2782
John McCall52a575a2009-08-29 08:11:13 +00002783static bool isInstantiationOf(CXXRecordDecl *Pattern,
2784 CXXRecordDecl *Instance) {
2785 Pattern = Pattern->getCanonicalDecl();
2786
2787 do {
2788 Instance = Instance->getCanonicalDecl();
2789 if (Pattern == Instance) return true;
2790 Instance = Instance->getInstantiatedFromMemberClass();
2791 } while (Instance);
2792
2793 return false;
2794}
2795
2796static bool isInstantiationOf(FunctionDecl *Pattern,
2797 FunctionDecl *Instance) {
2798 Pattern = Pattern->getCanonicalDecl();
2799
2800 do {
2801 Instance = Instance->getCanonicalDecl();
2802 if (Pattern == Instance) return true;
2803 Instance = Instance->getInstantiatedFromMemberFunction();
2804 } while (Instance);
2805
2806 return false;
2807}
2808
2809static bool isInstantiationOf(EnumDecl *Pattern,
2810 EnumDecl *Instance) {
2811 Pattern = Pattern->getCanonicalDecl();
2812
2813 do {
2814 Instance = Instance->getCanonicalDecl();
2815 if (Pattern == Instance) return true;
2816 Instance = Instance->getInstantiatedFromMemberEnum();
2817 } while (Instance);
2818
2819 return false;
2820}
2821
John McCalled976492009-12-04 22:46:56 +00002822static bool isInstantiationOf(UsingShadowDecl *Pattern,
2823 UsingShadowDecl *Instance,
2824 ASTContext &C) {
2825 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2826}
2827
2828static bool isInstantiationOf(UsingDecl *Pattern,
2829 UsingDecl *Instance,
2830 ASTContext &C) {
2831 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2832}
2833
John McCall7ba107a2009-11-18 02:36:19 +00002834static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2835 UsingDecl *Instance,
2836 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002837 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002838}
2839
2840static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002841 UsingDecl *Instance,
2842 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002843 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002844}
2845
John McCall52a575a2009-08-29 08:11:13 +00002846static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2847 VarDecl *Instance) {
2848 assert(Instance->isStaticDataMember());
2849
2850 Pattern = Pattern->getCanonicalDecl();
2851
2852 do {
2853 Instance = Instance->getCanonicalDecl();
2854 if (Pattern == Instance) return true;
2855 Instance = Instance->getInstantiatedFromStaticDataMember();
2856 } while (Instance);
2857
2858 return false;
2859}
2860
John McCalled976492009-12-04 22:46:56 +00002861// Other is the prospective instantiation
2862// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002863static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002864 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002865 if (UnresolvedUsingTypenameDecl *UUD
2866 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2867 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2868 return isInstantiationOf(UUD, UD, Ctx);
2869 }
2870 }
2871
2872 if (UnresolvedUsingValueDecl *UUD
2873 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002874 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2875 return isInstantiationOf(UUD, UD, Ctx);
2876 }
2877 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002878
Anders Carlsson0d8df782009-08-29 19:37:28 +00002879 return false;
2880 }
Mike Stump1eb44332009-09-09 15:08:12 +00002881
John McCall52a575a2009-08-29 08:11:13 +00002882 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2883 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002884
John McCall52a575a2009-08-29 08:11:13 +00002885 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2886 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002887
John McCall52a575a2009-08-29 08:11:13 +00002888 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2889 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002890
Douglas Gregor7caa6822009-07-24 20:34:43 +00002891 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002892 if (Var->isStaticDataMember())
2893 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2894
2895 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2896 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002897
Douglas Gregor0d696532009-09-28 06:34:35 +00002898 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2899 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2900
Douglas Gregored9c0f92009-10-29 00:04:11 +00002901 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2902 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2903 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2904 PartialSpec);
2905
Anders Carlssond8b285f2009-09-01 04:26:58 +00002906 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2907 if (!Field->getDeclName()) {
2908 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002909 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002910 cast<FieldDecl>(D);
2911 }
2912 }
Mike Stump1eb44332009-09-09 15:08:12 +00002913
John McCalled976492009-12-04 22:46:56 +00002914 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2915 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2916
2917 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2918 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2919
Douglas Gregor815215d2009-05-27 05:35:12 +00002920 return D->getDeclName() && isa<NamedDecl>(Other) &&
2921 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2922}
2923
2924template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002925static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002926 NamedDecl *D,
2927 ForwardIterator first,
2928 ForwardIterator last) {
2929 for (; first != last; ++first)
2930 if (isInstantiationOf(Ctx, D, *first))
2931 return cast<NamedDecl>(*first);
2932
2933 return 0;
2934}
2935
John McCall02cace72009-08-28 07:59:38 +00002936/// \brief Finds the instantiation of the given declaration context
2937/// within the current instantiation.
2938///
2939/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002940DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002941 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002942 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002943 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002944 return cast_or_null<DeclContext>(ID);
2945 } else return DC;
2946}
2947
Douglas Gregored961e72009-05-27 17:54:46 +00002948/// \brief Find the instantiation of the given declaration within the
2949/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002950///
2951/// This routine is intended to be used when \p D is a declaration
2952/// referenced from within a template, that needs to mapped into the
2953/// corresponding declaration within an instantiation. For example,
2954/// given:
2955///
2956/// \code
2957/// template<typename T>
2958/// struct X {
2959/// enum Kind {
2960/// KnownValue = sizeof(T)
2961/// };
2962///
2963/// bool getKind() const { return KnownValue; }
2964/// };
2965///
2966/// template struct X<int>;
2967/// \endcode
2968///
2969/// In the instantiation of X<int>::getKind(), we need to map the
2970/// EnumConstantDecl for KnownValue (which refers to
2971/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002972/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2973/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002974NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002975 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002976 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002977 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002978 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002979 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002980 // D is a local of some kind. Look into the map of local
2981 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002982 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2983 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2984 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002985
Chris Lattner57ad3782011-02-17 20:34:02 +00002986 if (Found) {
2987 if (Decl *FD = Found->dyn_cast<Decl *>())
2988 return cast<NamedDecl>(FD);
2989
2990 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2991 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2992 }
2993
2994 // If we didn't find the decl, then we must have a label decl that hasn't
2995 // been found yet. Lazily instantiate it and return it now.
2996 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002997
Chris Lattner57ad3782011-02-17 20:34:02 +00002998 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
2999 assert(Inst && "Failed to instantiate label??");
3000
3001 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3002 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003003 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003004
Douglas Gregore95b4092009-09-16 18:34:49 +00003005 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3006 if (!Record->isDependentContext())
3007 return D;
3008
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003009 // If the RecordDecl is actually the injected-class-name or a
3010 // "templated" declaration for a class template, class template
3011 // partial specialization, or a member class of a class template,
3012 // substitute into the injected-class-name of the class template
3013 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00003014 QualType T;
3015 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3016
3017 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00003018 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00003019 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3020 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00003021 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00003022
3023 // If we call SubstType with an InjectedClassNameType here we
3024 // can end up in an infinite loop.
3025 T = Context.getTypeDeclType(Record);
3026 assert(isa<InjectedClassNameType>(T) &&
3027 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00003028 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00003029 }
Douglas Gregore95b4092009-09-16 18:34:49 +00003030
3031 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003032 // Substitute into the injected-class-name to get the type
3033 // corresponding to the instantiation we want, which may also be
3034 // the current instantiation (if we're in a template
3035 // definition). This substitution should never fail, since we
3036 // know we can instantiate the injected-class-name or we
3037 // wouldn't have gotten to the injected-class-name!
3038
3039 // FIXME: Can we use the CurrentInstantiationScope to avoid this
3040 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00003041 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00003042 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
3043
3044 if (!T->isDependentType()) {
3045 assert(T->isRecordType() && "Instantiation must produce a record type");
3046 return T->getAs<RecordType>()->getDecl();
3047 }
3048
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003049 // We are performing "partial" template instantiation to create
3050 // the member declarations for the members of a class template
3051 // specialization. Therefore, D is actually referring to something
3052 // in the current instantiation. Look through the current
3053 // context, which contains actual instantiations, to find the
3054 // instantiation of the "current instantiation" that D refers
3055 // to.
3056 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003057 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00003058 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003059 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003060 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00003061 if (isInstantiationOf(ClassTemplate,
3062 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00003063 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003064
3065 if (!DC->isDependentContext())
3066 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00003067 }
3068
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003069 // We're performing "instantiation" of a member of the current
3070 // instantiation while we are type-checking the
3071 // definition. Compute the declaration context and return that.
3072 assert(!SawNonDependentContext &&
3073 "No dependent context while instantiating record");
3074 DeclContext *DC = computeDeclContext(T);
3075 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00003076 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003077 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00003078 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003079
Douglas Gregore95b4092009-09-16 18:34:49 +00003080 // Fall through to deal with other dependent record types (e.g.,
3081 // anonymous unions in class templates).
3082 }
John McCall52a575a2009-08-29 08:11:13 +00003083
Douglas Gregore95b4092009-09-16 18:34:49 +00003084 if (!ParentDC->isDependentContext())
3085 return D;
3086
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003087 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003088 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003089 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003090
Douglas Gregor815215d2009-05-27 05:35:12 +00003091 if (ParentDC != D->getDeclContext()) {
3092 // We performed some kind of instantiation in the parent context,
3093 // so now we need to look into the instantiated parent context to
3094 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003095
John McCall3cb0ebd2010-03-10 03:28:59 +00003096 // If our context used to be dependent, we may need to instantiate
3097 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003098 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003099 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003100 if (!Spec->isDependentContext()) {
3101 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003102 const RecordType *Tag = T->getAs<RecordType>();
3103 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003104 if (Tag->isBeingDefined())
3105 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003106 if (!Tag->isBeingDefined() &&
3107 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3108 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003109
3110 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003111 }
3112 }
3113
Douglas Gregor815215d2009-05-27 05:35:12 +00003114 NamedDecl *Result = 0;
3115 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003116 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003117 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3118 } else {
3119 // Since we don't have a name for the entity we're looking for,
3120 // our only option is to walk through all of the declarations to
3121 // find that name. This will occur in a few cases:
3122 //
3123 // - anonymous struct/union within a template
3124 // - unnamed class/struct/union/enum within a template
3125 //
3126 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003127 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003128 ParentDC->decls_begin(),
3129 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003130 }
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003132 if (!Result) {
3133 if (isa<UsingShadowDecl>(D)) {
3134 // UsingShadowDecls can instantiate to nothing because of using hiding.
3135 } else if (Diags.hasErrorOccurred()) {
3136 // We've already complained about something, so most likely this
3137 // declaration failed to instantiate. There's no point in complaining
3138 // further, since this is normal in invalid code.
3139 } else if (IsBeingInstantiated) {
3140 // The class in which this member exists is currently being
3141 // instantiated, and we haven't gotten around to instantiating this
3142 // member yet. This can happen when the code uses forward declarations
3143 // of member classes, and introduces ordering dependencies via
3144 // template instantiation.
3145 Diag(Loc, diag::err_member_not_yet_instantiated)
3146 << D->getDeclName()
3147 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3148 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3149 } else {
3150 // We should have found something, but didn't.
3151 llvm_unreachable("Unable to find instantiation of declaration!");
3152 }
3153 }
3154
Douglas Gregor815215d2009-05-27 05:35:12 +00003155 D = Result;
3156 }
3157
Douglas Gregor815215d2009-05-27 05:35:12 +00003158 return D;
3159}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003160
Mike Stump1eb44332009-09-09 15:08:12 +00003161/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003162/// instantiations we have seen until this point.
Douglas Gregor78844032011-04-22 22:25:37 +00003163///
3164/// \returns true if anything was instantiated.
3165bool Sema::PerformPendingInstantiations(bool LocalOnly) {
3166 bool InstantiatedAnything = false;
Douglas Gregor60406be2010-01-16 22:29:39 +00003167 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003168 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003169 PendingImplicitInstantiation Inst;
3170
3171 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003172 Inst = PendingInstantiations.front();
3173 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003174 } else {
3175 Inst = PendingLocalImplicitInstantiations.front();
3176 PendingLocalImplicitInstantiations.pop_front();
3177 }
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Douglas Gregor7caa6822009-07-24 20:34:43 +00003179 // Instantiate function definitions
3180 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003181 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3182 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003183 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3184 TSK_ExplicitInstantiationDefinition;
3185 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3186 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003187 InstantiatedAnything = true;
Douglas Gregor7caa6822009-07-24 20:34:43 +00003188 continue;
3189 }
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Douglas Gregor7caa6822009-07-24 20:34:43 +00003191 // Instantiate static data member definitions.
3192 VarDecl *Var = cast<VarDecl>(Inst.first);
3193 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003194
Chandler Carruth291b4412010-02-13 10:17:50 +00003195 // Don't try to instantiate declarations if the most recent redeclaration
3196 // is invalid.
3197 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3198 continue;
3199
3200 // Check if the most recent declaration has changed the specialization kind
3201 // and removed the need for implicit instantiation.
3202 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3203 case TSK_Undeclared:
3204 assert(false && "Cannot instantitiate an undeclared specialization.");
3205 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003206 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003207 continue; // No longer need to instantiate this type.
3208 case TSK_ExplicitInstantiationDefinition:
3209 // We only need an instantiation if the pending instantiation *is* the
3210 // explicit instantiation.
3211 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003212 case TSK_ImplicitInstantiation:
3213 break;
3214 }
3215
John McCallf312b1e2010-08-26 23:41:50 +00003216 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3217 "instantiating static data member "
3218 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Chandler Carruth58e390e2010-08-25 08:27:02 +00003220 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3221 TSK_ExplicitInstantiationDefinition;
3222 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3223 DefinitionRequired);
Douglas Gregor78844032011-04-22 22:25:37 +00003224 InstantiatedAnything = true;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003225 }
Douglas Gregor78844032011-04-22 22:25:37 +00003226
3227 return InstantiatedAnything;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003228}
John McCall0c01d182010-03-24 05:22:00 +00003229
3230void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3231 const MultiLevelTemplateArgumentList &TemplateArgs) {
3232 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3233 E = Pattern->ddiag_end(); I != E; ++I) {
3234 DependentDiagnostic *DD = *I;
3235
3236 switch (DD->getKind()) {
3237 case DependentDiagnostic::Access:
3238 HandleDependentAccessCheck(*DD, TemplateArgs);
3239 break;
3240 }
3241 }
3242}