blob: c39f0062586734dd511c5665ba72055666d4acf5 [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 Gregoraba43bb2009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.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;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000032
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000033 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000034 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000035 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000036
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000037 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000038 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000039
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000040 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;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000048
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000049 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000050 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000051 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000052
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000053 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000054 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000055
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000056 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000057 return false;
58}
59
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +000060// Include attribute instantiation code.
61#include "clang/Sema/AttrTemplateInstantiate.inc"
62
Richard Smithf6565a92013-02-22 08:32:16 +000063static void instantiateDependentAlignedAttr(
64 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
65 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
66 if (Aligned->isAlignmentExpr()) {
67 // The alignment expression is a constant expression.
68 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
69 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
70 if (!Result.isInvalid())
71 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
72 Aligned->getSpellingListIndex(), IsPackExpansion);
73 } else {
74 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
75 TemplateArgs, Aligned->getLocation(),
76 DeclarationName());
77 if (Result)
78 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
79 Aligned->getSpellingListIndex(), IsPackExpansion);
80 }
81}
82
83static void instantiateDependentAlignedAttr(
84 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
85 const AlignedAttr *Aligned, Decl *New) {
86 if (!Aligned->isPackExpansion()) {
87 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
88 return;
89 }
90
91 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
92 if (Aligned->isAlignmentExpr())
93 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
94 Unexpanded);
95 else
96 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
97 Unexpanded);
98 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
99
100 // Determine whether we can expand this attribute pack yet.
101 bool Expand = true, RetainExpansion = false;
102 Optional<unsigned> NumExpansions;
103 // FIXME: Use the actual location of the ellipsis.
104 SourceLocation EllipsisLoc = Aligned->getLocation();
105 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
106 Unexpanded, TemplateArgs, Expand,
107 RetainExpansion, NumExpansions))
108 return;
109
110 if (!Expand) {
111 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
112 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
113 } else {
114 for (unsigned I = 0; I != *NumExpansions; ++I) {
115 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
116 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
117 }
118 }
119}
120
John McCall1d8d1cc2010-08-01 02:01:53 +0000121void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000122 const Decl *Tmpl, Decl *New,
123 LateInstantiatedAttrVec *LateAttrs,
124 LocalInstantiationScope *OuterMostScope) {
Sean Huntcf807c42010-08-18 23:23:40 +0000125 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
126 i != e; ++i) {
127 const Attr *TmplAttr = *i;
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000128
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000129 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smithf6565a92013-02-22 08:32:16 +0000130 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
131 if (Aligned && Aligned->isAlignmentDependent()) {
132 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
133 continue;
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000134 }
135
Richard Smithf6565a92013-02-22 08:32:16 +0000136 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000137 if (TmplAttr->isLateParsed() && LateAttrs) {
138 // Late parsed attributes must be instantiated and attached after the
139 // enclosing class has been instantiated. See Sema::InstantiateClass.
140 LocalInstantiationScope *Saved = 0;
141 if (CurrentInstantiationScope)
142 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
143 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
144 } else {
Benjamin Kramer5bbc3852012-02-06 11:13:08 +0000145 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
146 *this, TemplateArgs);
Rafael Espindola31c195a2012-05-15 14:09:55 +0000147 if (NewAttr)
148 New->addAttr(NewAttr);
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000149 }
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000150 }
151}
152
Douglas Gregor4f722be2009-03-25 15:45:12 +0000153Decl *
154TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000155 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000156}
157
158Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000159TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
160 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
161 D->getIdentifier());
162 Owner->addDecl(Inst);
163 return Inst;
164}
165
166Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000167TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000168 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000169}
170
John McCall3dbd3d52010-02-16 06:53:13 +0000171Decl *
172TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
173 NamespaceAliasDecl *Inst
174 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
175 D->getNamespaceLoc(),
176 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000177 D->getIdentifier(),
178 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000179 D->getTargetNameLoc(),
180 D->getNamespace());
181 Owner->addDecl(Inst);
182 return Inst;
183}
184
Richard Smith3e4c6c42011-05-05 21:57:07 +0000185Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
186 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000187 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000188 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000189 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000190 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000191 DI = SemaRef.SubstType(DI, TemplateArgs,
192 D->getLocation(), D->getDeclName());
193 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000195 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000197 } else {
198 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199 }
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Richard Smithb5b37d12012-10-23 00:32:41 +0000201 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
202 // libstdc++ relies upon this bug in its implementation of common_type.
203 // If we happen to be processing that implementation, fake up the g++ ?:
204 // semantics. See LWG issue 2141 for more information on the bug.
205 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
206 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
207 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
208 DT->isReferenceType() &&
209 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
210 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
211 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
212 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
213 // Fold it to the (non-reference) type which g++ would have produced.
214 DI = SemaRef.Context.getTrivialTypeSourceInfo(
215 DI->getType().getNonReferenceType());
216
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000217 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000218 TypedefNameDecl *Typedef;
219 if (IsTypeAlias)
220 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
221 D->getLocation(), D->getIdentifier(), DI);
222 else
223 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
224 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000225 if (Invalid)
226 Typedef->setInvalidDecl();
227
John McCallcde5a402011-02-01 08:20:08 +0000228 // If the old typedef was the name for linkage purposes of an anonymous
229 // tag decl, re-establish that relationship for the new typedef.
230 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
231 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregorc61361b2013-03-08 22:15:15 +0000232 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCallcde5a402011-02-01 08:20:08 +0000233 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000234 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
235 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000236 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000237 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000238
Douglas Gregoref96ee02012-01-14 16:38:05 +0000239 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000240 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
241 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000242 if (!InstPrev)
243 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000244
Rafael Espindola5df37bd2011-12-26 22:42:47 +0000245 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
246
247 // If the typedef types are not identical, reject them.
248 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
249
250 Typedef->setPreviousDeclaration(InstPrevTypedef);
John McCall5126fd02009-12-30 00:31:22 +0000251 }
252
John McCall1d8d1cc2010-08-01 02:01:53 +0000253 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000254
John McCall46460a62010-01-20 21:53:11 +0000255 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000257 return Typedef;
258}
259
Richard Smith162e1c12011-04-15 14:24:37 +0000260Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000261 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
262 Owner->addDecl(Typedef);
263 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000264}
265
266Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000267 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
268 Owner->addDecl(Typedef);
269 return Typedef;
270}
271
272Decl *
273TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
274 // Create a local instantiation scope for this type alias template, which
275 // will contain the instantiations of the template parameters.
276 LocalInstantiationScope Scope(SemaRef);
277
278 TemplateParameterList *TempParams = D->getTemplateParameters();
279 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
280 if (!InstParams)
281 return 0;
282
283 TypeAliasDecl *Pattern = D->getTemplatedDecl();
284
285 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000286 if (Pattern->getPreviousDecl()) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000287 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000288 if (!Found.empty()) {
289 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3e4c6c42011-05-05 21:57:07 +0000290 }
291 }
292
293 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
294 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
295 if (!AliasInst)
296 return 0;
297
298 TypeAliasTemplateDecl *Inst
299 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
300 D->getDeclName(), InstParams, AliasInst);
301 if (PrevAliasTemplate)
302 Inst->setPreviousDeclaration(PrevAliasTemplate);
303
304 Inst->setAccess(D->getAccess());
305
306 if (!PrevAliasTemplate)
307 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000308
Richard Smith3e4c6c42011-05-05 21:57:07 +0000309 Owner->addDecl(Inst);
310
311 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000312}
313
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000314Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000315 // If this is the variable for an anonymous struct or union,
316 // instantiate the anonymous struct/union type first.
317 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
318 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
319 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
320 return 0;
321
John McCallce3ff2b2009-08-25 22:02:44 +0000322 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000323 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000324 TemplateArgs,
325 D->getTypeSpecStartLoc(),
326 D->getDeclName());
327 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000328 return 0;
329
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000330 if (DI->getType()->isFunctionType()) {
331 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
332 << D->isStaticDataMember() << DI->getType();
333 return 0;
334 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000335
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000336 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000337 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000338 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000339 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000340 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000341 D->getStorageClass(),
342 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000343 Var->setThreadSpecified(D->isThreadSpecified());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000344 Var->setInitStyle(D->getInitStyle());
Richard Smithad762fc2011-04-14 22:09:26 +0000345 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Richard Smith796c1a12012-01-19 22:46:17 +0000346 Var->setConstexpr(D->isConstexpr());
Mike Stump1eb44332009-09-09 15:08:12 +0000347
John McCallb6217662010-03-15 10:12:16 +0000348 // Substitute the nested name specifier, if any.
349 if (SubstQualifier(D, Var))
350 return 0;
351
Mike Stump1eb44332009-09-09 15:08:12 +0000352 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000353 // out-of-line, the instantiation will have the same lexical
354 // context (which will be a namespace scope) as the template.
355 if (D->isOutOfLine())
356 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000357
John McCall46460a62010-01-20 21:53:11 +0000358 Var->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000359
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000360 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000361 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000362 Var->setReferenced(D->isReferenced());
363 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000364
Richard Smith671b3212013-02-22 04:55:39 +0000365 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
366
367 if (Var->hasAttrs())
368 SemaRef.CheckAlignasUnderalignment(Var);
369
Mike Stump390b4cc2009-05-16 07:39:55 +0000370 // FIXME: In theory, we could have a previous declaration for variables that
371 // are not static data members.
John McCall68263142009-11-18 22:49:29 +0000372 // FIXME: having to fake up a LookupResult is dumb.
373 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000374 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000375 if (D->isStaticDataMember())
376 SemaRef.LookupQualifiedName(Previous, Owner, false);
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000377
378 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000379 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000380 SemaRef.inferObjCARCLifetime(Var))
381 Var->setInvalidDecl();
382
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +0000383 SemaRef.CheckVariableDeclaration(Var, Previous);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Douglas Gregor7caa6822009-07-24 20:34:43 +0000385 if (D->isOutOfLine()) {
Richard Smith3e9ea0b2011-12-21 00:25:33 +0000386 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000387 Owner->makeDeclVisibleInContext(Var);
388 } else {
389 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000390 if (Owner->isFunctionOrMethod())
391 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000392 }
Richard Smithbe507b62013-02-01 08:12:08 +0000393
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000394 // Link instantiations of static data members back to the template from
395 // which they were instantiated.
396 if (Var->isStaticDataMember())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000397 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000398 TSK_ImplicitInstantiation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000399
Douglas Gregor60c93c92010-02-09 07:26:29 +0000400 if (Var->getAnyInitializer()) {
401 // We already have an initializer in the class.
402 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000403 if (Var->isStaticDataMember() && !D->isOutOfLine())
Richard Smithadb1d4c2012-07-22 23:45:10 +0000404 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000405 else
Richard Smithadb1d4c2012-07-22 23:45:10 +0000406 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000407
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000408 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000409 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
410 D->getInitStyle() == VarDecl::CallInit);
411 if (!Init.isInvalid()) {
Richard Smith34b41d92011-02-20 03:19:35 +0000412 bool TypeMayContainAuto = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000413 if (Init.get()) {
414 bool DirectInit = D->isDirectInit();
415 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
416 TypeMayContainAuto);
417 } else
Eli Friedman6aeaa602012-01-05 22:34:08 +0000418 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000419 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000420 // FIXME: Not too happy about invalidating the declaration
421 // because of a bogus initializer.
422 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000423 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000424
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000425 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000426 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
427 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000428 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000429
Richard Smithe3499ca2011-06-21 23:42:09 +0000430 // Diagnose unused local variables with dependent types, where the diagnostic
431 // will have been deferred.
432 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
433 D->getType()->isDependentType())
Douglas Gregor5764f612010-05-08 23:05:03 +0000434 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000435
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000436 return Var;
437}
438
Abramo Bagnara6206d532010-06-05 05:09:32 +0000439Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
440 AccessSpecDecl* AD
441 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
442 D->getAccessSpecifierLoc(), D->getColonLoc());
443 Owner->addHiddenDecl(AD);
444 return AD;
445}
446
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000447Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
448 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000449 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000450 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000451 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000452 DI = SemaRef.SubstType(DI, TemplateArgs,
453 D->getLocation(), D->getDeclName());
454 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000455 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000456 Invalid = true;
457 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000458 // C++ [temp.arg.type]p3:
459 // If a declaration acquires a function type through a type
460 // dependent on a template-parameter and this causes a
461 // declaration that does not use the syntactic form of a
462 // function declarator to have function type, the program is
463 // ill-formed.
464 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000465 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000466 Invalid = true;
467 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000468 } else {
469 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000470 }
471
472 Expr *BitWidth = D->getBitWidth();
473 if (Invalid)
474 BitWidth = 0;
475 else if (BitWidth) {
Richard Smithf6702a32011-12-20 02:08:33 +0000476 // The bit-width expression is a constant expression.
477 EnterExpressionEvaluationContext Unevaluated(SemaRef,
478 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
John McCall60d7b3a2010-08-24 06:29:42 +0000480 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000481 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000482 if (InstantiatedBitWidth.isInvalid()) {
483 Invalid = true;
484 BitWidth = 0;
485 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000486 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000487 }
488
John McCall07fb6be2009-10-22 23:33:21 +0000489 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
490 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000491 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000492 D->getLocation(),
493 D->isMutable(),
494 BitWidth,
Richard Smithca523302012-06-10 03:12:00 +0000495 D->getInClassInitStyle(),
Richard Smith703b6012012-05-23 04:22:22 +0000496 D->getInnerLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000497 D->getAccess(),
498 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000499 if (!Field) {
500 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000501 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000504 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000505
Richard Smithbe507b62013-02-01 08:12:08 +0000506 if (Field->hasAttrs())
507 SemaRef.CheckAlignasUnderalignment(Field);
508
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000509 if (Invalid)
510 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000512 if (!Field->getDeclName()) {
513 // Keep track of where this decl came from.
514 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000515 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000516 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
517 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000518 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000519 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000520 }
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000522 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000523 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000524 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000525
526 return Field;
527}
528
Francois Pichet87c2e122010-11-21 06:08:52 +0000529Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
530 NamedDecl **NamedChain =
531 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
532
533 int i = 0;
534 for (IndirectFieldDecl::chain_iterator PI =
535 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000536 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000537 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000538 TemplateArgs);
539 if (!Next)
540 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000541
Douglas Gregorb7107222011-03-04 19:46:35 +0000542 NamedChain[i++] = Next;
543 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000544
Francois Pichet40e17752010-12-09 10:07:54 +0000545 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000546 IndirectFieldDecl* IndirectField
547 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000548 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000549 NamedChain, D->getChainingSize());
550
551
552 IndirectField->setImplicit(D->isImplicit());
553 IndirectField->setAccess(D->getAccess());
554 Owner->addDecl(IndirectField);
555 return IndirectField;
556}
557
John McCall02cace72009-08-28 07:59:38 +0000558Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000559 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000560 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000561 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000562 TypeSourceInfo *InstTy;
563 // If this is an unsupported friend, don't bother substituting template
564 // arguments into it. The actual type referred to won't be used by any
565 // parts of Clang, and may not be valid for instantiating. Just use the
566 // same info for the instantiated friend.
567 if (D->isUnsupportedFriend()) {
568 InstTy = Ty;
569 } else {
570 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
571 D->getLocation(), DeclarationName());
572 }
573 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000574 return 0;
John McCall02cace72009-08-28 07:59:38 +0000575
Richard Smithd6f80da2012-09-20 01:31:00 +0000576 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000577 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000578 if (!FD)
579 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000580
Douglas Gregor06245bf2010-04-07 17:57:12 +0000581 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000582 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000583 Owner->addDecl(FD);
584 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000585 }
586
Douglas Gregor06245bf2010-04-07 17:57:12 +0000587 NamedDecl *ND = D->getFriendDecl();
588 assert(ND && "friend decl must be a decl or a type!");
589
John McCallaf2094e2010-04-08 09:05:18 +0000590 // All of the Visit implementations for the various potential friend
591 // declarations have to be carefully written to work for friend
592 // objects, with the most important detail being that the target
593 // decl should almost certainly not be placed in Owner.
594 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000595 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000596
John McCall02cace72009-08-28 07:59:38 +0000597 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000598 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000599 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000600 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000601 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000602 Owner->addDecl(FD);
603 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000604}
605
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000606Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
607 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Richard Smithf6702a32011-12-20 02:08:33 +0000609 // The expression in a static assertion is a constant expression.
610 EnterExpressionEvaluationContext Unevaluated(SemaRef,
611 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000612
John McCall60d7b3a2010-08-24 06:29:42 +0000613 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000614 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000615 if (InstantiatedAssertExpr.isInvalid())
616 return 0;
617
Richard Smithe3f470a2012-07-11 22:37:56 +0000618 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000619 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000620 D->getMessage(),
621 D->getRParenLoc(),
622 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000623}
624
625Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000626 EnumDecl *PrevDecl = 0;
627 if (D->getPreviousDecl()) {
628 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
629 D->getPreviousDecl(),
630 TemplateArgs);
631 if (!Prev) return 0;
632 PrevDecl = cast<EnumDecl>(Prev);
633 }
634
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000635 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000636 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000637 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000638 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000639 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000640 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000641 // If we have type source information for the underlying type, it means it
642 // has been explicitly set by the user. Perform substitution on it before
643 // moving on.
644 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000645 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
646 DeclarationName());
647 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000648 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000649 else
650 Enum->setIntegerTypeSourceInfo(NewTI);
651 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000652 assert(!D->getIntegerType()->isDependentType()
653 && "Dependent type without type source info");
654 Enum->setIntegerType(D->getIntegerType());
655 }
656 }
657
John McCall5b629aa2010-10-22 23:36:17 +0000658 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
659
Richard Smithf1c66b42012-03-14 23:13:10 +0000660 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000661 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000662 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000663 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000664
Richard Smith4ca93d92012-03-26 04:08:46 +0000665 EnumDecl *Def = D->getDefinition();
666 if (Def && Def != D) {
667 // If this is an out-of-line definition of an enum member template, check
668 // that the underlying types match in the instantiation of both
669 // declarations.
670 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
671 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
672 QualType DefnUnderlying =
673 SemaRef.SubstType(TI->getType(), TemplateArgs,
674 UnderlyingLoc, DeclarationName());
675 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
676 DefnUnderlying, Enum);
677 }
678 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000679
Douglas Gregor96084f12010-03-01 19:00:07 +0000680 if (D->getDeclContext()->isFunctionOrMethod())
681 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000682
Richard Smithf1c66b42012-03-14 23:13:10 +0000683 // C++11 [temp.inst]p1: The implicit instantiation of a class template
684 // specialization causes the implicit instantiation of the declarations, but
685 // not the definitions of scoped member enumerations.
686 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000687 // within a block scope, but we treat that much like a member template. Only
688 // instantiate the definition when visiting the definition in that case, since
689 // we will visit all redeclarations.
690 if (!Enum->isScoped() && Def &&
691 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000692 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000693
694 return Enum;
695}
696
697void TemplateDeclInstantiator::InstantiateEnumDefinition(
698 EnumDecl *Enum, EnumDecl *Pattern) {
699 Enum->startDefinition();
700
Richard Smith1af83c42012-03-23 03:33:32 +0000701 // Update the location to refer to the definition.
702 Enum->setLocation(Pattern->getLocation());
703
Chris Lattner5f9e2722011-07-23 10:55:15 +0000704 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000705
706 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000707 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
708 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000709 EC != ECEnd; ++EC) {
710 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000711 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000712 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000713 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000714 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000715 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000716
John McCallce3ff2b2009-08-25 22:02:44 +0000717 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000718 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000719
720 // Drop the initial value and continue.
721 bool isInvalid = false;
722 if (Value.isInvalid()) {
723 Value = SemaRef.Owned((Expr *)0);
724 isInvalid = true;
725 }
726
Mike Stump1eb44332009-09-09 15:08:12 +0000727 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000728 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
729 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000730 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000731
732 if (isInvalid) {
733 if (EnumConst)
734 EnumConst->setInvalidDecl();
735 Enum->setInvalidDecl();
736 }
737
738 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000739 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000740
John McCall3b85ecf2010-01-23 22:37:59 +0000741 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000742 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000743 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000744 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000745
Richard Smithf1c66b42012-03-14 23:13:10 +0000746 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
747 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000748 // If the enumeration is within a function or method, record the enum
749 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000750 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000751 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000752 }
753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Richard Smithf1c66b42012-03-14 23:13:10 +0000755 // FIXME: Fixup LBraceLoc
756 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
757 Enum->getRBraceLoc(), Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000758 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000759 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000760}
761
Douglas Gregor6477b692009-03-25 15:04:13 +0000762Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000763 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000764}
765
John McCalle29ba202009-08-20 01:44:21 +0000766Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000767 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
768
Douglas Gregor550d9b22009-10-31 17:21:17 +0000769 // Create a local instantiation scope for this class template, which
770 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000771 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000772 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000773 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000774 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000775 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000776
777 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000778
779 // Instantiate the qualifier. We have to do this first in case
780 // we're a friend declaration, because if we are then we need to put
781 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000782 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
783 if (QualifierLoc) {
784 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
785 TemplateArgs);
786 if (!QualifierLoc)
787 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000788 }
789
790 CXXRecordDecl *PrevDecl = 0;
791 ClassTemplateDecl *PrevClassTemplate = 0;
792
Douglas Gregoref96ee02012-01-14 16:38:05 +0000793 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000794 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000795 if (!Found.empty()) {
796 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky37574f52010-11-08 23:29:42 +0000797 if (PrevClassTemplate)
798 PrevDecl = PrevClassTemplate->getTemplatedDecl();
799 }
800 }
801
John McCall93ba8572010-03-25 06:39:04 +0000802 // If this isn't a friend, then it's a member template, in which
803 // case we just want to build the instantiation in the
804 // specialization. If it is a friend, we want to build it in
805 // the appropriate context.
806 DeclContext *DC = Owner;
807 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000808 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000809 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000810 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000811 DC = SemaRef.computeDeclContext(SS);
812 if (!DC) return 0;
813 } else {
814 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
815 Pattern->getDeclContext(),
816 TemplateArgs);
817 }
818
819 // Look for a previous declaration of the template in the owning
820 // context.
821 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
822 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
823 SemaRef.LookupQualifiedName(R, DC);
824
825 if (R.isSingleResult()) {
826 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
827 if (PrevClassTemplate)
828 PrevDecl = PrevClassTemplate->getTemplatedDecl();
829 }
830
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000831 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000832 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000833 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000834 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000835 return 0;
836 }
837
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000838 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000839 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000840 bool Complain = true;
841
842 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
843 // template for struct std::tr1::__detail::_Map_base, where the
844 // template parameters of the friend declaration don't match the
845 // template parameters of the original declaration. In this one
846 // case, we don't complain about the ill-formed friend
847 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000848 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000849 Pattern->getIdentifier()->isStr("_Map_base") &&
850 DC->isNamespace() &&
851 cast<NamespaceDecl>(DC)->getIdentifier() &&
852 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
853 DeclContext *DCParent = DC->getParent();
854 if (DCParent->isNamespace() &&
855 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
856 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
857 DeclContext *DCParent2 = DCParent->getParent();
858 if (DCParent2->isNamespace() &&
859 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
860 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
861 DCParent2->getParent()->isTranslationUnit())
862 Complain = false;
863 }
864 }
865
John McCall93ba8572010-03-25 06:39:04 +0000866 TemplateParameterList *PrevParams
867 = PrevClassTemplate->getTemplateParameters();
868
869 // Make sure the parameter lists match.
870 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000871 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000872 Sema::TPL_TemplateMatch)) {
873 if (Complain)
874 return 0;
875
876 AdoptedPreviousTemplateParams = true;
877 InstParams = PrevParams;
878 }
John McCall93ba8572010-03-25 06:39:04 +0000879
880 // Do some additional validation, then merge default arguments
881 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000882 if (!AdoptedPreviousTemplateParams &&
883 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000884 Sema::TPC_ClassTemplate))
885 return 0;
886 }
887 }
888
John McCalle29ba202009-08-20 01:44:21 +0000889 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000890 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000891 Pattern->getLocStart(), Pattern->getLocation(),
892 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000893 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000894
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000895 if (QualifierLoc)
896 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000897
John McCalle29ba202009-08-20 01:44:21 +0000898 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000899 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
900 D->getIdentifier(), InstParams, RecordInst,
901 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000902 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000903
John McCall93ba8572010-03-25 06:39:04 +0000904 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000905 if (PrevClassTemplate)
906 Inst->setAccess(PrevClassTemplate->getAccess());
907 else
908 Inst->setAccess(D->getAccess());
909
John McCall93ba8572010-03-25 06:39:04 +0000910 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
911 // TODO: do we want to track the instantiation progeny of this
912 // friend target decl?
913 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000914 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000915 if (!PrevClassTemplate)
916 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000917 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000918
Douglas Gregorf0510d42009-10-12 23:11:44 +0000919 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000920 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000921 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000922
Douglas Gregor259571e2009-10-30 22:42:42 +0000923 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000924 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000925 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000926 Inst->setLexicalDeclContext(Owner);
927 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000928 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000929 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000930
Abramo Bagnara4c515482011-11-26 13:33:46 +0000931 if (D->isOutOfLine()) {
932 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
933 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
934 }
935
John McCalle29ba202009-08-20 01:44:21 +0000936 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000937
938 if (!PrevClassTemplate) {
939 // Queue up any out-of-line partial specializations of this member
940 // class template; the client will force their instantiation once
941 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000942 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000943 D->getPartialSpecializations(PartialSpecs);
944 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
945 if (PartialSpecs[I]->isOutOfLine())
946 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
947 }
948
John McCalle29ba202009-08-20 01:44:21 +0000949 return Inst;
950}
951
Douglas Gregord60e1052009-08-27 16:57:43 +0000952Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000953TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
954 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000955 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000956
Douglas Gregored9c0f92009-10-29 00:04:11 +0000957 // Lookup the already-instantiated declaration in the instantiation
958 // of the class template and return that.
959 DeclContext::lookup_result Found
960 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000961 if (Found.empty())
Douglas Gregored9c0f92009-10-29 00:04:11 +0000962 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000963
Douglas Gregored9c0f92009-10-29 00:04:11 +0000964 ClassTemplateDecl *InstClassTemplate
David Blaikie3bc93e32012-12-19 00:45:41 +0000965 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregored9c0f92009-10-29 00:04:11 +0000966 if (!InstClassTemplate)
967 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000968
Douglas Gregord65587f2010-11-10 19:44:59 +0000969 if (ClassTemplatePartialSpecializationDecl *Result
970 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
971 return Result;
972
973 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000974}
975
976Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000977TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000978 // Create a local instantiation scope for this function template, which
979 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000980 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +0000981 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000982 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000983
Douglas Gregord60e1052009-08-27 16:57:43 +0000984 TemplateParameterList *TempParams = D->getTemplateParameters();
985 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000986 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000987 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000988
Douglas Gregora735b202009-10-13 14:39:41 +0000989 FunctionDecl *Instantiated = 0;
990 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000991 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +0000992 InstParams));
993 else
994 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000995 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +0000996 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000997
Douglas Gregora735b202009-10-13 14:39:41 +0000998 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000999 return 0;
1000
Mike Stump1eb44332009-09-09 15:08:12 +00001001 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001002 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001003 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001004 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001005 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001006 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001007 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001008
John McCallb1a56e72010-03-26 23:10:15 +00001009 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1010
John McCalle976ffe2009-12-14 23:19:40 +00001011 // Link the instantiation back to the pattern *unless* this is a
1012 // non-definition friend declaration.
1013 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001014 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001015 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001016
John McCallb1a56e72010-03-26 23:10:15 +00001017 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001018 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001019 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001020 } else if (InstTemplate->getDeclContext()->isRecord() &&
1021 !D->getPreviousDecl()) {
1022 SemaRef.CheckFriendAccess(InstTemplate);
1023 }
John McCallb1a56e72010-03-26 23:10:15 +00001024
Douglas Gregord60e1052009-08-27 16:57:43 +00001025 return InstTemplate;
1026}
1027
Douglas Gregord475b8d2009-03-25 21:17:03 +00001028Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1029 CXXRecordDecl *PrevDecl = 0;
1030 if (D->isInjectedClassName())
1031 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001032 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001033 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001034 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001035 TemplateArgs);
1036 if (!Prev) return 0;
1037 PrevDecl = cast<CXXRecordDecl>(Prev);
1038 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001039
1040 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001041 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001042 D->getLocStart(), D->getLocation(),
1043 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001044
1045 // Substitute the nested name specifier, if any.
1046 if (SubstQualifier(D, Record))
1047 return 0;
1048
Douglas Gregord475b8d2009-03-25 21:17:03 +00001049 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001050 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1051 // the tag decls introduced by friend class declarations don't have an access
1052 // specifier. Remove once this area of the code gets sorted out.
1053 if (D->getAccess() != AS_none)
1054 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001055 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001056 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001057
John McCall02cace72009-08-28 07:59:38 +00001058 // If the original function was part of a friend declaration,
1059 // inherit its namespace state.
1060 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1061 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1062
Douglas Gregor9901c572010-05-21 00:31:19 +00001063 // Make sure that anonymous structs and unions are recorded.
1064 if (D->isAnonymousStructOrUnion()) {
1065 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001066 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001067 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1068 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001069
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001070 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001071 return Record;
1072}
1073
Douglas Gregor71074fd2012-09-13 21:56:43 +00001074/// \brief Adjust the given function type for an instantiation of the
1075/// given declaration, to cope with modifications to the function's type that
1076/// aren't reflected in the type-source information.
1077///
1078/// \param D The declaration we're instantiating.
1079/// \param TInfo The already-instantiated type.
1080static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1081 FunctionDecl *D,
1082 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001083 const FunctionProtoType *OrigFunc
1084 = D->getType()->castAs<FunctionProtoType>();
1085 const FunctionProtoType *NewFunc
1086 = TInfo->getType()->castAs<FunctionProtoType>();
1087 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1088 return TInfo->getType();
1089
1090 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1091 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1092 return Context.getFunctionType(NewFunc->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00001093 ArrayRef<QualType>(NewFunc->arg_type_begin(),
1094 NewFunc->getNumArgs()),
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001095 NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001096}
1097
John McCall02cace72009-08-28 07:59:38 +00001098/// Normal class members are of more specific types and therefore
1099/// don't make it here. This function serves two purposes:
1100/// 1) instantiating function templates
1101/// 2) substituting friend declarations
1102/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001103Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001104 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001105 // Check whether there is already a function template specialization for
1106 // this declaration.
1107 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001108 if (FunctionTemplate && !TemplateParams) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001109 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001110 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001112 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001113 FunctionDecl *SpecFunc
1114 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1115 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Douglas Gregor127102b2009-06-29 20:59:39 +00001117 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001118 if (SpecFunc)
1119 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001120 }
Mike Stump1eb44332009-09-09 15:08:12 +00001121
John McCallb0cb0222010-03-27 05:57:59 +00001122 bool isFriend;
1123 if (FunctionTemplate)
1124 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1125 else
1126 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1127
Douglas Gregor79c22782010-01-16 20:21:20 +00001128 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001129 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001130 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001131 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001132 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Chris Lattner5f9e2722011-07-23 10:55:15 +00001134 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001135 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001136 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001137 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001138 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001139
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001140 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1141 if (QualifierLoc) {
1142 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1143 TemplateArgs);
1144 if (!QualifierLoc)
1145 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001146 }
1147
John McCall68b6b872010-02-06 01:50:47 +00001148 // If we're instantiating a local function declaration, put the result
1149 // in the owner; otherwise we need to find the instantiated context.
1150 DeclContext *DC;
1151 if (D->getDeclContext()->isFunctionOrMethod())
1152 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001153 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001154 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001155 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001156 DC = SemaRef.computeDeclContext(SS);
1157 if (!DC) return 0;
1158 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001159 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001160 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001161 }
John McCall68b6b872010-02-06 01:50:47 +00001162
John McCall02cace72009-08-28 07:59:38 +00001163 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001164 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001165 D->getNameInfo(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001166 D->getStorageClass(), D->getStorageClassAsWritten(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001167 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001168 D->isConstexpr());
John McCallb6217662010-03-15 10:12:16 +00001169
Richard Smithd4497dd2013-01-25 00:08:28 +00001170 if (D->isInlined())
1171 Function->setImplicitlyInline();
1172
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001173 if (QualifierLoc)
1174 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001175
John McCallb1a56e72010-03-26 23:10:15 +00001176 DeclContext *LexicalDC = Owner;
1177 if (!isFriend && D->isOutOfLine()) {
1178 assert(D->getDeclContext()->isFileContext());
1179 LexicalDC = D->getDeclContext();
1180 }
1181
1182 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Douglas Gregore53060f2009-06-25 22:08:12 +00001184 // Attach the parameters
Douglas Gregor5cbe1012011-07-05 18:30:26 +00001185 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
Douglas Gregor1d441ee2011-06-22 18:16:25 +00001186 // Adopt the already-instantiated parameters into our own context.
1187 for (unsigned P = 0; P < Params.size(); ++P)
1188 if (Params[P])
1189 Params[P]->setOwningFunction(Function);
1190 } else {
1191 // Since we were instantiated via a typedef of a function type, create
1192 // new parameters.
1193 const FunctionProtoType *Proto
1194 = Function->getType()->getAs<FunctionProtoType>();
1195 assert(Proto && "No function prototype in template instantiation?");
1196 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1197 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1198 ParmVarDecl *Param
1199 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1200 *AI);
1201 Param->setScopeInfo(0, Params.size());
1202 Params.push_back(Param);
1203 }
1204 }
David Blaikie4278c652011-09-21 18:16:56 +00001205 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001206
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001207 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001208 if (TemplateParams) {
1209 // Our resulting instantiation is actually a function template, since we
1210 // are substituting only the outer template parameters. For example, given
1211 //
1212 // template<typename T>
1213 // struct X {
1214 // template<typename U> friend void f(T, U);
1215 // };
1216 //
1217 // X<int> x;
1218 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001219 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001220 // which means substituting int for T, but leaving "f" as a friend function
1221 // template.
1222 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001223 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001224 Function->getLocation(),
1225 Function->getDeclName(),
1226 TemplateParams, Function);
1227 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001228
1229 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001230
1231 if (isFriend && D->isThisDeclarationADefinition()) {
1232 // TODO: should we remember this connection regardless of whether
1233 // the friend declaration provided a body?
1234 FunctionTemplate->setInstantiatedFromMemberTemplate(
1235 D->getDescribedFunctionTemplate());
1236 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001237 } else if (FunctionTemplate) {
1238 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001239 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001240 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001241 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001242 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001243 Innermost.first,
1244 Innermost.second),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001245 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001246 } else if (isFriend) {
1247 // Note, we need this connection even if the friend doesn't have a body.
1248 // Its body may exist but not have been attached yet due to deferred
1249 // parsing.
1250 // FIXME: It might be cleaner to set this when attaching the body to the
1251 // friend function declaration, however that would require finding all the
1252 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001253 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001254 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001255
Douglas Gregore53060f2009-06-25 22:08:12 +00001256 if (InitFunctionInstantiation(Function, D))
1257 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001258
John McCallaf2094e2010-04-08 09:05:18 +00001259 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001260
John McCall68263142009-11-18 22:49:29 +00001261 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1262 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1263
John McCallaf2094e2010-04-08 09:05:18 +00001264 if (DependentFunctionTemplateSpecializationInfo *Info
1265 = D->getDependentSpecializationInfo()) {
1266 assert(isFriend && "non-friend has dependent specialization info?");
1267
1268 // This needs to be set now for future sanity.
1269 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1270
1271 // Instantiate the explicit template arguments.
1272 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1273 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001274 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1275 ExplicitArgs, TemplateArgs))
1276 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001277
1278 // Map the candidate templates to their instantiations.
1279 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1280 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1281 Info->getTemplate(I),
1282 TemplateArgs);
1283 if (!Temp) return 0;
1284
1285 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1286 }
1287
1288 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1289 &ExplicitArgs,
1290 Previous))
1291 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001292
John McCallaf2094e2010-04-08 09:05:18 +00001293 isExplicitSpecialization = true;
1294
1295 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001296 // Look only into the namespace where the friend would be declared to
1297 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001298 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001299 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001300
Douglas Gregora735b202009-10-13 14:39:41 +00001301 // In C++, the previous declaration we find might be a tag type
1302 // (class or enum). In this case, the new declaration will hide the
1303 // tag type. Note that this does does not apply if we're declaring a
1304 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001305 if (Previous.isSingleTagDecl())
1306 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001307 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001308
John McCall9f54ad42009-12-10 09:41:52 +00001309 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001310 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001311
John McCall76d32642010-04-24 01:30:58 +00001312 NamedDecl *PrincipalDecl = (TemplateParams
1313 ? cast<NamedDecl>(FunctionTemplate)
1314 : Function);
1315
Douglas Gregora735b202009-10-13 14:39:41 +00001316 // If the original function was part of a friend declaration,
1317 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001318 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001319 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001320 if (TemplateParams)
Douglas Gregoref96ee02012-01-14 16:38:05 +00001321 PrevDecl = FunctionTemplate->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001322 else
Douglas Gregoref96ee02012-01-14 16:38:05 +00001323 PrevDecl = Function->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001324
1325 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001326 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001327
Gabor Greif77535df2010-08-30 22:25:56 +00001328 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001329
Richard Smith53e53512011-10-19 00:54:10 +00001330 // C++98 [temp.friend]p5: When a function is defined in a friend function
1331 // declaration in a class template, the function is defined at each
1332 // instantiation of the class template. The function is defined even if it
1333 // is never used.
1334 // C++11 [temp.friend]p4: When a function is defined in a friend function
1335 // declaration in a class template, the function is instantiated when the
1336 // function is odr-used.
1337 //
1338 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1339 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001340 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001341 SemaRef.Diags.getDiagnosticLevel(
1342 diag::warn_cxx98_compat_friend_redefinition,
1343 Function->getLocation())
1344 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001345 D->isThisDeclarationADefinition()) {
1346 // Check for a function body.
1347 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001348 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001349 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001350 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001351 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001352 diag::warn_cxx98_compat_friend_redefinition :
1353 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001354 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001355 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001356 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001357 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001358 // Check for redefinitions due to other instantiations of this or
1359 // a similar friend function.
1360 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1361 REnd = Function->redecls_end();
1362 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001363 if (*R == Function)
1364 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001365 switch (R->getFriendObjectKind()) {
1366 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001367 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001368 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001369 if (MemberSpecializationInfo *MSInfo
1370 = Function->getMemberSpecializationInfo()) {
1371 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1372 SourceLocation Loc = R->getLocation(); // FIXME
1373 MSInfo->setPointOfInstantiation(Loc);
1374 SemaRef.PendingLocalImplicitInstantiations.push_back(
1375 std::make_pair(Function, Loc));
1376 queuedInstantiation = true;
1377 }
1378 }
1379 }
1380 break;
1381 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001382 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001383 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001384 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001385 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001386 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001387 diag::warn_cxx98_compat_friend_redefinition :
1388 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001389 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001390 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001391 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001392 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001393 break;
1394 }
1395 }
1396 }
1397 }
Douglas Gregora735b202009-10-13 14:39:41 +00001398 }
1399
John McCall76d32642010-04-24 01:30:58 +00001400 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1401 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1402 PrincipalDecl->setNonMemberOperator();
1403
Sean Hunteb88ae52011-05-23 21:07:59 +00001404 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001405 return Function;
1406}
1407
Douglas Gregord60e1052009-08-27 16:57:43 +00001408Decl *
1409TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001410 TemplateParameterList *TemplateParams,
1411 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001412 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001413 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001414 // We are creating a function template specialization from a function
1415 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001416 // specialization for this particular set of template arguments.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001417 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001418 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001420 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001421 FunctionDecl *SpecFunc
1422 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1423 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Douglas Gregor6b906862009-08-21 00:16:32 +00001425 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001426 if (SpecFunc)
1427 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001428 }
1429
John McCallb0cb0222010-03-27 05:57:59 +00001430 bool isFriend;
1431 if (FunctionTemplate)
1432 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1433 else
1434 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1435
Douglas Gregor79c22782010-01-16 20:21:20 +00001436 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001437 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001438 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001439 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001440
John McCall4eab39f2010-10-19 02:26:41 +00001441 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001442 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001443 unsigned NumTempParamLists = 0;
1444 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1445 TempParamLists.set_size(NumTempParamLists);
1446 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1447 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1448 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1449 if (!InstParams)
1450 return NULL;
1451 TempParamLists[I] = InstParams;
1452 }
1453 }
1454
Chris Lattner5f9e2722011-07-23 10:55:15 +00001455 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001456 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001457 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001458 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001459 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001460
Abramo Bagnara723df242010-12-14 22:11:44 +00001461 // \brief If the type of this function, after ignoring parentheses,
1462 // is not *directly* a function type, then we're instantiating a function
1463 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001464 //
1465 // typedef int functype(int, int);
1466 // functype func;
1467 //
1468 // In this case, we'll just go instantiate the ParmVarDecls that we
1469 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001470 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001471 assert(!Params.size() && "Instantiating type could not yield parameters");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001472 SmallVector<QualType, 4> ParamTypes;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001473 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1474 D->getNumParams(), TemplateArgs, ParamTypes,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001475 &Params))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001476 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001477 }
1478
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001479 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1480 if (QualifierLoc) {
1481 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001482 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001483 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001484 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001485 }
1486
1487 DeclContext *DC = Owner;
1488 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001489 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001490 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001491 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001492 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001493
1494 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1495 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001496 } else {
1497 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1498 D->getDeclContext(),
1499 TemplateArgs);
1500 }
1501 if (!DC) return 0;
1502 }
1503
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001504 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001505 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001506 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001508 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001509 DeclarationNameInfo NameInfo
1510 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001511 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001512 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001513 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001514 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001515 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001516 false, Constructor->isConstexpr());
Douglas Gregor17e32f32009-08-21 22:43:28 +00001517 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001518 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001519 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001520 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001521 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001522 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001523 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001524 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001525 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001526 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001527 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001528 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001529 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001530 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001531 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001532 D->isStatic(),
1533 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001534 D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001535 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001536 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001537
Richard Smithd4497dd2013-01-25 00:08:28 +00001538 if (D->isInlined())
1539 Method->setImplicitlyInline();
1540
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001541 if (QualifierLoc)
1542 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001543
Douglas Gregord60e1052009-08-27 16:57:43 +00001544 if (TemplateParams) {
1545 // Our resulting instantiation is actually a function template, since we
1546 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001547 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001548 // template<typename T>
1549 // struct X {
1550 // template<typename U> void f(T, U);
1551 // };
1552 //
1553 // X<int> x;
1554 //
1555 // We are instantiating the member template "f" within X<int>, which means
1556 // substituting int for T, but leaving "f" as a member function template.
1557 // Build the function template itself.
1558 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1559 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001560 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001561 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001562 if (isFriend) {
1563 FunctionTemplate->setLexicalDeclContext(Owner);
1564 FunctionTemplate->setObjectOfFriendDecl(true);
1565 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001566 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001567 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001568 } else if (FunctionTemplate) {
1569 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001570 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001571 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001572 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001573 TemplateArgumentList::CreateCopy(SemaRef.Context,
1574 Innermost.first,
1575 Innermost.second),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001576 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001577 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001578 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001579 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001580 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001581
Mike Stump1eb44332009-09-09 15:08:12 +00001582 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001583 // out-of-line, the instantiation will have the same lexical
1584 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001585 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001586 if (NumTempParamLists)
1587 Method->setTemplateParameterListsInfo(SemaRef.Context,
1588 NumTempParamLists,
1589 TempParamLists.data());
1590
John McCallb0cb0222010-03-27 05:57:59 +00001591 Method->setLexicalDeclContext(Owner);
1592 Method->setObjectOfFriendDecl(true);
1593 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001594 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Douglas Gregor5545e162009-03-24 00:38:23 +00001596 // Attach the parameters
1597 for (unsigned P = 0; P < Params.size(); ++P)
1598 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001599 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001600
1601 if (InitMethodInstantiation(Method, D))
1602 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001603
Abramo Bagnara25777432010-08-11 22:01:17 +00001604 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1605 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
John McCallb0cb0222010-03-27 05:57:59 +00001607 if (!FunctionTemplate || TemplateParams || isFriend) {
1608 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Douglas Gregordec06662009-08-21 18:42:58 +00001610 // In C++, the previous declaration we find might be a tag type
1611 // (class or enum). In this case, the new declaration will hide the
1612 // tag type. Note that this does does not apply if we're declaring a
1613 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001614 if (Previous.isSingleTagDecl())
1615 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001616 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001617
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001618 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001619 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001620
Douglas Gregor4ba31362009-12-01 17:24:26 +00001621 if (D->isPure())
1622 SemaRef.CheckPureMethod(Method, SourceRange());
1623
John McCall1f2e1a92012-08-10 03:15:35 +00001624 // Propagate access. For a non-friend declaration, the access is
1625 // whatever we're propagating from. For a friend, it should be the
1626 // previous declaration we just found.
1627 if (isFriend && Method->getPreviousDecl())
1628 Method->setAccess(Method->getPreviousDecl()->getAccess());
1629 else
1630 Method->setAccess(D->getAccess());
1631 if (FunctionTemplate)
1632 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001633
Anders Carlsson9eefa222011-01-20 06:52:44 +00001634 SemaRef.CheckOverrideControl(Method);
1635
Eli Friedman3bc45152011-11-15 22:39:08 +00001636 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001637 if (D->isExplicitlyDefaulted())
1638 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001639 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001640 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001641
John McCall1f2e1a92012-08-10 03:15:35 +00001642 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001643 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001644 // do nothing
1645
1646 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001647 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001648 // do nothing
1649
1650 // Otherwise, check access to friends and make them visible.
1651 } else if (isFriend) {
1652 // We only need to re-check access for methods which we didn't
1653 // manage to match during parsing.
1654 if (!D->getPreviousDecl())
1655 SemaRef.CheckFriendAccess(Method);
1656
1657 Record->makeDeclVisibleInContext(Method);
1658
1659 // Otherwise, add the declaration. We don't need to do this for
1660 // class-scope specializations because we'll have matched them with
1661 // the appropriate template.
1662 } else if (!IsClassScopeSpecialization) {
1663 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001664 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001665
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001666 return Method;
1667}
1668
Douglas Gregor615c5d42009-03-24 16:43:20 +00001669Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001670 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001671}
1672
Douglas Gregor03b2b072009-03-24 00:15:49 +00001673Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001674 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001675}
1676
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001677Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001678 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001679}
1680
Douglas Gregor6477b692009-03-25 15:04:13 +00001681ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001682 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1683 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001684}
1685
John McCalle29ba202009-08-20 01:44:21 +00001686Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1687 TemplateTypeParmDecl *D) {
1688 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001689 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001690
John McCalle29ba202009-08-20 01:44:21 +00001691 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001692 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1693 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001694 D->getDepth() - TemplateArgs.getNumLevels(),
1695 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001696 D->wasDeclaredWithTypename(),
1697 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001698 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001699
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001700 if (D->hasDefaultArgument())
1701 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1702
1703 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001704 // scope.
1705 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001706
John McCalle29ba202009-08-20 01:44:21 +00001707 return Inst;
1708}
1709
Douglas Gregor33642df2009-10-23 23:25:44 +00001710Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1711 NonTypeTemplateParmDecl *D) {
1712 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001713 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001714 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1715 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001716 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001717 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001718 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001719 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001720
1721 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001722 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001723 // expansion of types. Substitute into each of the expanded types.
1724 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1725 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1726 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1727 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1728 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001729 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001730 D->getDeclName());
1731 if (!NewDI)
1732 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001733
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001734 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1735 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1736 D->getLocation());
1737 if (NewT.isNull())
1738 return 0;
1739 ExpandedParameterPackTypes.push_back(NewT);
1740 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001741
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001742 IsExpandedParameterPack = true;
1743 DI = D->getTypeSourceInfo();
1744 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001745 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001746 // The non-type template parameter pack's type is a pack expansion of types.
1747 // Determine whether we need to expand this parameter pack into separate
1748 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001749 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001750 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001751 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001752 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001753
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001754 // Determine whether the set of unexpanded parameter packs can and should
1755 // be expanded.
1756 bool Expand = true;
1757 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001758 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001759 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001760 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001761 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1762 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001763 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001764 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001765 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001766 NumExpansions))
1767 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001768
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001769 if (Expand) {
1770 for (unsigned I = 0; I != *NumExpansions; ++I) {
1771 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1772 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001773 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001774 D->getDeclName());
1775 if (!NewDI)
1776 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001777
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001778 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1779 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1780 NewDI->getType(),
1781 D->getLocation());
1782 if (NewT.isNull())
1783 return 0;
1784 ExpandedParameterPackTypes.push_back(NewT);
1785 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001786
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001787 // Note that we have an expanded parameter pack. The "type" of this
1788 // expanded parameter pack is the original expansion type, but callers
1789 // will end up using the expanded parameter pack types for type-checking.
1790 IsExpandedParameterPack = true;
1791 DI = D->getTypeSourceInfo();
1792 T = DI->getType();
1793 } else {
1794 // We cannot fully expand the pack expansion now, so substitute into the
1795 // pattern and create a new pack expansion type.
1796 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1797 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001798 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001799 D->getDeclName());
1800 if (!NewPattern)
1801 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001802
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001803 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1804 NumExpansions);
1805 if (!DI)
1806 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001807
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001808 T = DI->getType();
1809 }
1810 } else {
1811 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001812 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001813 D->getLocation(), D->getDeclName());
1814 if (!DI)
1815 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001816
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001817 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001818 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001819 D->getLocation());
1820 if (T.isNull()) {
1821 T = SemaRef.Context.IntTy;
1822 Invalid = true;
1823 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001824 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001825
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001826 NonTypeTemplateParmDecl *Param;
1827 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001828 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001829 D->getInnerLocStart(),
1830 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001831 D->getDepth() - TemplateArgs.getNumLevels(),
1832 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001833 D->getIdentifier(), T,
1834 DI,
1835 ExpandedParameterPackTypes.data(),
1836 ExpandedParameterPackTypes.size(),
1837 ExpandedParameterPackTypesAsWritten.data());
1838 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001839 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001840 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001841 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001842 D->getDepth() - TemplateArgs.getNumLevels(),
1843 D->getPosition(),
1844 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001845 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001846
Douglas Gregor9a299e02011-03-04 17:52:15 +00001847 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001848 if (Invalid)
1849 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001850
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001851 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001852
1853 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001854 // scope.
1855 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001856 return Param;
1857}
1858
Richard Smith6964b3f2012-09-07 02:06:42 +00001859static void collectUnexpandedParameterPacks(
1860 Sema &S,
1861 TemplateParameterList *Params,
1862 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1863 for (TemplateParameterList::const_iterator I = Params->begin(),
1864 E = Params->end(); I != E; ++I) {
1865 if ((*I)->isTemplateParameterPack())
1866 continue;
1867 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1868 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1869 Unexpanded);
1870 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1871 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1872 Unexpanded);
1873 }
1874}
1875
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001876Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001877TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1878 TemplateTemplateParmDecl *D) {
1879 // Instantiate the template parameter list of the template template parameter.
1880 TemplateParameterList *TempParams = D->getTemplateParameters();
1881 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001882 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1883
1884 bool IsExpandedParameterPack = false;
1885
1886 if (D->isExpandedParameterPack()) {
1887 // The template template parameter pack is an already-expanded pack
1888 // expansion of template parameters. Substitute into each of the expanded
1889 // parameters.
1890 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1891 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1892 I != N; ++I) {
1893 LocalInstantiationScope Scope(SemaRef);
1894 TemplateParameterList *Expansion =
1895 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1896 if (!Expansion)
1897 return 0;
1898 ExpandedParams.push_back(Expansion);
1899 }
1900
1901 IsExpandedParameterPack = true;
1902 InstParams = TempParams;
1903 } else if (D->isPackExpansion()) {
1904 // The template template parameter pack expands to a pack of template
1905 // template parameters. Determine whether we need to expand this parameter
1906 // pack into separate parameters.
1907 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1908 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1909 Unexpanded);
1910
1911 // Determine whether the set of unexpanded parameter packs can and should
1912 // be expanded.
1913 bool Expand = true;
1914 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001915 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001916 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1917 TempParams->getSourceRange(),
1918 Unexpanded,
1919 TemplateArgs,
1920 Expand, RetainExpansion,
1921 NumExpansions))
1922 return 0;
1923
1924 if (Expand) {
1925 for (unsigned I = 0; I != *NumExpansions; ++I) {
1926 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1927 LocalInstantiationScope Scope(SemaRef);
1928 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1929 if (!Expansion)
1930 return 0;
1931 ExpandedParams.push_back(Expansion);
1932 }
1933
1934 // Note that we have an expanded parameter pack. The "type" of this
1935 // expanded parameter pack is the original expansion type, but callers
1936 // will end up using the expanded parameter pack types for type-checking.
1937 IsExpandedParameterPack = true;
1938 InstParams = TempParams;
1939 } else {
1940 // We cannot fully expand the pack expansion now, so just substitute
1941 // into the pattern.
1942 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1943
1944 LocalInstantiationScope Scope(SemaRef);
1945 InstParams = SubstTemplateParams(TempParams);
1946 if (!InstParams)
1947 return 0;
1948 }
1949 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00001950 // Perform the actual substitution of template parameters within a new,
1951 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001952 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001953 InstParams = SubstTemplateParams(TempParams);
1954 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00001955 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001956 }
1957
Douglas Gregor9106ef72009-11-11 16:58:32 +00001958 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00001959 TemplateTemplateParmDecl *Param;
1960 if (IsExpandedParameterPack)
1961 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1962 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001963 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00001964 D->getPosition(),
1965 D->getIdentifier(), InstParams,
1966 ExpandedParams);
1967 else
1968 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1969 D->getLocation(),
1970 D->getDepth() - TemplateArgs.getNumLevels(),
1971 D->getPosition(),
1972 D->isParameterPack(),
1973 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001974 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001975 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001976
1977 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00001978 // scope.
1979 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001980
Douglas Gregor9106ef72009-11-11 16:58:32 +00001981 return Param;
1982}
1983
Douglas Gregor48c32a72009-11-17 06:07:40 +00001984Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001985 // Using directives are never dependent (and never contain any types or
1986 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001987
Douglas Gregor48c32a72009-11-17 06:07:40 +00001988 UsingDirectiveDecl *Inst
1989 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001990 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001991 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001992 D->getIdentLocation(),
1993 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001994 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00001995
1996 // Add the using directive to its declaration context
1997 // only if this is not a function or method.
1998 if (!Owner->isFunctionOrMethod())
1999 Owner->addDecl(Inst);
2000
Douglas Gregor48c32a72009-11-17 06:07:40 +00002001 return Inst;
2002}
2003
John McCalled976492009-12-04 22:46:56 +00002004Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002005
2006 // The nested name specifier may be dependent, for example
2007 // template <typename T> struct t {
2008 // struct s1 { T f1(); };
2009 // struct s2 : s1 { using s1::f1; };
2010 // };
2011 // template struct t<int>;
2012 // Here, in using s1::f1, s1 refers to t<T>::s1;
2013 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002014 NestedNameSpecifierLoc QualifierLoc
2015 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2016 TemplateArgs);
2017 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002018 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002019
2020 // The name info is non-dependent, so no transformation
2021 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002022 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002023
John McCall9f54ad42009-12-10 09:41:52 +00002024 // We only need to do redeclaration lookups if we're in a class
2025 // scope (in fact, it's not really even possible in non-class
2026 // scopes).
2027 bool CheckRedeclaration = Owner->isRecord();
2028
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002029 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2030 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002031
John McCalled976492009-12-04 22:46:56 +00002032 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00002033 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002034 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002035 NameInfo,
John McCalled976492009-12-04 22:46:56 +00002036 D->isTypeName());
2037
Douglas Gregor5149f372011-02-25 15:54:31 +00002038 CXXScopeSpec SS;
2039 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002040 if (CheckRedeclaration) {
2041 Prev.setHideTags(false);
2042 SemaRef.LookupQualifiedName(Prev, Owner);
2043
2044 // Check for invalid redeclarations.
2045 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2046 D->isTypeName(), SS,
2047 D->getLocation(), Prev))
2048 NewUD->setInvalidDecl();
2049
2050 }
2051
2052 if (!NewUD->isInvalidDecl() &&
2053 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00002054 D->getLocation()))
2055 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002056
John McCalled976492009-12-04 22:46:56 +00002057 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2058 NewUD->setAccess(D->getAccess());
2059 Owner->addDecl(NewUD);
2060
John McCall9f54ad42009-12-10 09:41:52 +00002061 // Don't process the shadow decls for an invalid decl.
2062 if (NewUD->isInvalidDecl())
2063 return NewUD;
2064
Richard Smithc5a89a12012-04-02 01:30:27 +00002065 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2066 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2067 NewUD->setInvalidDecl();
2068 return NewUD;
2069 }
2070
John McCall323c3102009-12-22 22:26:37 +00002071 bool isFunctionScope = Owner->isFunctionOrMethod();
2072
John McCall9f54ad42009-12-10 09:41:52 +00002073 // Process the shadow decls.
2074 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2075 I != E; ++I) {
2076 UsingShadowDecl *Shadow = *I;
2077 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002078 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2079 Shadow->getLocation(),
2080 Shadow->getTargetDecl(),
2081 TemplateArgs));
2082 if (!InstTarget)
2083 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002084
2085 if (CheckRedeclaration &&
2086 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2087 continue;
2088
2089 UsingShadowDecl *InstShadow
2090 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2091 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002092
2093 if (isFunctionScope)
2094 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002095 }
John McCalled976492009-12-04 22:46:56 +00002096
2097 return NewUD;
2098}
2099
2100Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002101 // Ignore these; we handle them in bulk when processing the UsingDecl.
2102 return 0;
John McCalled976492009-12-04 22:46:56 +00002103}
2104
John McCall7ba107a2009-11-18 02:36:19 +00002105Decl * TemplateDeclInstantiator
2106 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002107 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002108 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002109 TemplateArgs);
2110 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002111 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002113 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002114 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002116 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002117 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002118 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002119 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002120 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002121 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002122 /*instantiation*/ true,
2123 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002124 if (UD)
John McCalled976492009-12-04 22:46:56 +00002125 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2126
John McCall7ba107a2009-11-18 02:36:19 +00002127 return UD;
2128}
2129
2130Decl * TemplateDeclInstantiator
2131 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002132 NestedNameSpecifierLoc QualifierLoc
2133 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2134 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002135 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002136
John McCall7ba107a2009-11-18 02:36:19 +00002137 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002138 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002139
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002140 DeclarationNameInfo NameInfo
2141 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2142
John McCall7ba107a2009-11-18 02:36:19 +00002143 NamedDecl *UD =
2144 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002145 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002146 /*instantiation*/ true,
2147 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002148 if (UD)
John McCalled976492009-12-04 22:46:56 +00002149 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2150
Anders Carlsson0d8df782009-08-29 19:37:28 +00002151 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002152}
2153
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002154
2155Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2156 ClassScopeFunctionSpecializationDecl *Decl) {
2157 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002158 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2159 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002160
2161 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2162 Sema::ForRedeclaration);
2163
Nico Weber6b020092012-06-25 17:21:05 +00002164 TemplateArgumentListInfo TemplateArgs;
2165 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2166 if (Decl->hasExplicitTemplateArgs()) {
2167 TemplateArgs = Decl->templateArgs();
2168 TemplateArgsPtr = &TemplateArgs;
2169 }
2170
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002171 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002172 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2173 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002174 NewFD->setInvalidDecl();
2175 return NewFD;
2176 }
2177
2178 // Associate the specialization with the pattern.
2179 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2180 assert(Specialization && "Class scope Specialization is null");
2181 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2182
2183 return NewFD;
2184}
2185
John McCallce3ff2b2009-08-25 22:02:44 +00002186Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002187 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002188 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002189 if (D->isInvalidDecl())
2190 return 0;
2191
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002192 return Instantiator.Visit(D);
2193}
2194
John McCalle29ba202009-08-20 01:44:21 +00002195/// \brief Instantiates a nested template parameter list in the current
2196/// instantiation context.
2197///
2198/// \param L The parameter list to instantiate
2199///
2200/// \returns NULL if there was an error
2201TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002202TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002203 // Get errors for all the parameters before bailing out.
2204 bool Invalid = false;
2205
2206 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002207 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002208 ParamVector Params;
2209 Params.reserve(N);
2210 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2211 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002212 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002213 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002214 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002215 }
2216
2217 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002218 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002219 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002220
2221 TemplateParameterList *InstL
2222 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2223 L->getLAngleLoc(), &Params.front(), N,
2224 L->getRAngleLoc());
2225 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002226}
John McCalle29ba202009-08-20 01:44:21 +00002227
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002228/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002229/// specialization.
2230///
2231/// \param ClassTemplate the (instantiated) class template that is partially
2232// specialized by the instantiation of \p PartialSpec.
2233///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002234/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002235/// specialization that we are instantiating.
2236///
Douglas Gregord65587f2010-11-10 19:44:59 +00002237/// \returns The instantiated partial specialization, if successful; otherwise,
2238/// NULL to indicate an error.
2239ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002240TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2241 ClassTemplateDecl *ClassTemplate,
2242 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002243 // Create a local instantiation scope for this class template partial
2244 // specialization, which will contain the instantiations of the template
2245 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002246 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002247
Douglas Gregored9c0f92009-10-29 00:04:11 +00002248 // Substitute into the template parameters of the class template partial
2249 // specialization.
2250 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2251 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2252 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002253 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002254
Douglas Gregored9c0f92009-10-29 00:04:11 +00002255 // Substitute into the template arguments of the class template partial
2256 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00002257 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002258 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2259 PartialSpec->getNumTemplateArgsAsWritten(),
Douglas Gregore02e2622010-12-22 21:19:48 +00002260 InstTemplateArgs, TemplateArgs))
2261 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002262
Douglas Gregored9c0f92009-10-29 00:04:11 +00002263 // Check that the template argument list is well-formed for this
2264 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002265 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002266 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002267 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002268 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002269 false,
2270 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002271 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002272
2273 // Figure out where to insert this class template partial specialization
2274 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002275 void *InsertPos = 0;
2276 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002277 = ClassTemplate->findPartialSpecialization(Converted.data(),
2278 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002279
Douglas Gregored9c0f92009-10-29 00:04:11 +00002280 // Build the canonical type that describes the converted template
2281 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002282 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002283 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002284 Converted.data(),
2285 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002286
2287 // Build the fully-sugared type for this class template
2288 // specialization as the user wrote in the specialization
2289 // itself. This means that we'll pretty-print the type retrieved
2290 // from the specialization's declaration the way that the user
2291 // actually wrote the specialization, rather than formatting the
2292 // name based on the "canonical" representation used to store the
2293 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002294 TypeSourceInfo *WrittenTy
2295 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2296 TemplateName(ClassTemplate),
2297 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002298 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002299 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002300
Douglas Gregored9c0f92009-10-29 00:04:11 +00002301 if (PrevDecl) {
2302 // We've already seen a partial specialization with the same template
2303 // parameters and template arguments. This can happen, for example, when
2304 // substituting the outer template arguments ends up causing two
2305 // class template partial specializations of a member class template
2306 // to have identical forms, e.g.,
2307 //
2308 // template<typename T, typename U>
2309 // struct Outer {
2310 // template<typename X, typename Y> struct Inner;
2311 // template<typename Y> struct Inner<T, Y>;
2312 // template<typename Y> struct Inner<U, Y>;
2313 // };
2314 //
2315 // Outer<int, int> outer; // error: the partial specializations of Inner
2316 // // have the same signature.
2317 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002318 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002319 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2320 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002321 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002322 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002323
2324
Douglas Gregored9c0f92009-10-29 00:04:11 +00002325 // Create the class template partial specialization declaration.
2326 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002327 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002328 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002329 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002330 PartialSpec->getLocStart(),
2331 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002332 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002333 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002334 Converted.data(),
2335 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002336 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002337 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002338 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002339 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002340 // Substitute the nested name specifier, if any.
2341 if (SubstQualifier(PartialSpec, InstPartialSpec))
2342 return 0;
2343
Douglas Gregored9c0f92009-10-29 00:04:11 +00002344 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002345 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002346
Douglas Gregored9c0f92009-10-29 00:04:11 +00002347 // Add this partial specialization to the set of class template partial
2348 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002349 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002350 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002351}
2352
John McCall21ef0fa2010-03-11 09:03:00 +00002353TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002354TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002355 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002356 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2357 assert(OldTInfo && "substituting function without type source info");
2358 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002359
2360 CXXRecordDecl *ThisContext = 0;
2361 unsigned ThisTypeQuals = 0;
2362 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2363 ThisContext = Method->getParent();
2364 ThisTypeQuals = Method->getTypeQualifiers();
2365 }
2366
John McCall6cd3b9f2010-04-09 17:38:44 +00002367 TypeSourceInfo *NewTInfo
2368 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2369 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002370 D->getDeclName(),
2371 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002372 if (!NewTInfo)
2373 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002374
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002375 if (NewTInfo != OldTInfo) {
2376 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002377 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002378 if (FunctionProtoTypeLoc OldProtoLoc =
2379 OldTL.getAs<FunctionProtoTypeLoc>()) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002380 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002381 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002382 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002383 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002384 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002385 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002386 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2387
David Blaikiedc84cd52013-02-20 22:23:23 +00002388 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002389 if (OldParam->isParameterPack())
2390 NumArgumentsInExpansion =
2391 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2392 TemplateArgs);
2393 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002394 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002395 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002396 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002397 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002398 Scope->InstantiatedLocal(OldParam, NewParam);
2399 } else {
2400 // Parameter pack expansion: make the instantiation an argument pack.
2401 Scope->MakeInstantiatedLocalArgPack(OldParam);
2402 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002403 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002404 Params.push_back(NewParam);
2405 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2406 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002407 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002408 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002409 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002410 } else {
2411 // The function type itself was not dependent and therefore no
2412 // substitution occurred. However, we still need to instantiate
2413 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002414 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002415 if (FunctionProtoTypeLoc OldProtoLoc =
2416 OldTL.getAs<FunctionProtoTypeLoc>()) {
2417 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
2418 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc.getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002419 if (!Parm)
2420 return 0;
2421 Params.push_back(Parm);
2422 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002423 }
2424 }
John McCall21ef0fa2010-03-11 09:03:00 +00002425 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002426}
2427
Richard Smithe6975e92012-04-17 00:58:00 +00002428/// Introduce the instantiated function parameters into the local
2429/// instantiation scope, and set the parameter names to those used
2430/// in the template.
2431static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2432 const FunctionDecl *PatternDecl,
2433 LocalInstantiationScope &Scope,
2434 const MultiLevelTemplateArgumentList &TemplateArgs) {
2435 unsigned FParamIdx = 0;
2436 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2437 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2438 if (!PatternParam->isParameterPack()) {
2439 // Simple case: not a parameter pack.
2440 assert(FParamIdx < Function->getNumParams());
2441 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2442 FunctionParam->setDeclName(PatternParam->getDeclName());
2443 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2444 ++FParamIdx;
2445 continue;
2446 }
2447
2448 // Expand the parameter pack.
2449 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002450 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002451 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002452 assert(NumArgumentsInExpansion &&
2453 "should only be called when all template arguments are known");
2454 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002455 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2456 FunctionParam->setDeclName(PatternParam->getDeclName());
2457 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2458 ++FParamIdx;
2459 }
2460 }
2461}
2462
2463static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2464 const FunctionProtoType *Proto,
2465 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002466 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2467
Richard Smithe6975e92012-04-17 00:58:00 +00002468 // C++11 [expr.prim.general]p3:
2469 // If a declaration declares a member function or member function
2470 // template of a class X, the expression this is a prvalue of type
2471 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2472 // and the end of the function-definition, member-declarator, or
2473 // declarator.
2474 CXXRecordDecl *ThisContext = 0;
2475 unsigned ThisTypeQuals = 0;
2476 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2477 ThisContext = Method->getParent();
2478 ThisTypeQuals = Method->getTypeQualifiers();
2479 }
2480 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002481 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002482
2483 // The function has an exception specification or a "noreturn"
2484 // attribute. Substitute into each of the exception types.
2485 SmallVector<QualType, 4> Exceptions;
2486 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2487 // FIXME: Poor location information!
2488 if (const PackExpansionType *PackExpansion
2489 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2490 // We have a pack expansion. Instantiate it.
2491 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2492 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2493 Unexpanded);
2494 assert(!Unexpanded.empty() &&
2495 "Pack expansion without parameter packs?");
2496
2497 bool Expand = false;
2498 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00002499 Optional<unsigned> NumExpansions
Richard Smithe6975e92012-04-17 00:58:00 +00002500 = PackExpansion->getNumExpansions();
2501 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2502 SourceRange(),
2503 Unexpanded,
2504 TemplateArgs,
2505 Expand,
2506 RetainExpansion,
2507 NumExpansions))
2508 break;
2509
2510 if (!Expand) {
2511 // We can't expand this pack expansion into separate arguments yet;
2512 // just substitute into the pattern and create a new pack expansion
2513 // type.
2514 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2515 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2516 TemplateArgs,
2517 New->getLocation(), New->getDeclName());
2518 if (T.isNull())
2519 break;
2520
2521 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2522 Exceptions.push_back(T);
2523 continue;
2524 }
2525
2526 // Substitute into the pack expansion pattern for each template
2527 bool Invalid = false;
2528 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2529 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2530
2531 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2532 TemplateArgs,
2533 New->getLocation(), New->getDeclName());
2534 if (T.isNull()) {
2535 Invalid = true;
2536 break;
2537 }
2538
2539 Exceptions.push_back(T);
2540 }
2541
2542 if (Invalid)
2543 break;
2544
2545 continue;
2546 }
2547
2548 QualType T
2549 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2550 New->getLocation(), New->getDeclName());
2551 if (T.isNull() ||
2552 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2553 continue;
2554
2555 Exceptions.push_back(T);
2556 }
2557 Expr *NoexceptExpr = 0;
2558 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2559 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2560 Sema::ConstantEvaluated);
2561 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2562 if (E.isUsable())
2563 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2564
2565 if (E.isUsable()) {
2566 NoexceptExpr = E.take();
2567 if (!NoexceptExpr->isTypeDependent() &&
2568 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002569 NoexceptExpr
2570 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2571 0, diag::err_noexcept_needs_constant_expression,
2572 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002573 }
2574 }
2575
2576 // Rebuild the function type
2577 const FunctionProtoType *NewProto
2578 = New->getType()->getAs<FunctionProtoType>();
2579 assert(NewProto && "Template instantiation without function prototype?");
2580
2581 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2582 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2583 EPI.NumExceptions = Exceptions.size();
2584 EPI.Exceptions = Exceptions.data();
2585 EPI.NoexceptExpr = NoexceptExpr;
2586
2587 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002588 ArrayRef<QualType>(NewProto->arg_type_begin(),
2589 NewProto->getNumArgs()),
Richard Smithe6975e92012-04-17 00:58:00 +00002590 EPI));
2591}
2592
2593void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2594 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002595 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2596 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002597 return;
2598
2599 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2600 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002601 if (Inst) {
2602 // We hit the instantiation depth limit. Clear the exception specification
2603 // so that our callers don't have to cope with EST_Uninstantiated.
2604 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2605 EPI.ExceptionSpecType = EST_None;
2606 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002607 ArrayRef<QualType>(Proto->arg_type_begin(),
2608 Proto->getNumArgs()),
Richard Smithb9d0b762012-07-27 04:22:15 +00002609 EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002610 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002611 }
Richard Smithe6975e92012-04-17 00:58:00 +00002612
2613 // Enter the scope of this instantiation. We don't use
2614 // PushDeclContext because we don't have a scope.
2615 Sema::ContextRAII savedContext(*this, Decl);
2616 LocalInstantiationScope Scope(*this);
2617
2618 MultiLevelTemplateArgumentList TemplateArgs =
2619 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2620
Richard Smith13bffc52012-04-19 00:08:28 +00002621 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2622 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002623
Richard Smith13bffc52012-04-19 00:08:28 +00002624 ::InstantiateExceptionSpec(*this, Decl,
2625 Template->getType()->castAs<FunctionProtoType>(),
2626 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002627}
2628
Mike Stump1eb44332009-09-09 15:08:12 +00002629/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002630/// declaration (New) from the corresponding fields of its template (Tmpl).
2631///
2632/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002633bool
2634TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002635 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002636 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002637 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Douglas Gregorcca9e962009-07-01 22:01:06 +00002639 // If we are performing substituting explicitly-specified template arguments
2640 // or deduced template arguments into a function template and we reach this
2641 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002642 // to keeping the new function template specialization. We therefore
2643 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002644 // into a template instantiation for this specific function template
2645 // specialization, which is not a SFINAE context, so that we diagnose any
2646 // further errors in the declaration itself.
2647 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2648 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2649 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2650 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002651 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002652 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002653 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002654 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002655 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002656 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002657 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002658 }
2659 }
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002661 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2662 assert(Proto && "Function template without prototype?");
2663
Sebastian Redl60618fa2011-03-12 11:50:43 +00002664 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00002665 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00002666
Richard Smithe6975e92012-04-17 00:58:00 +00002667 // DR1330: In C++11, defer instantiation of a non-trivial
2668 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00002669 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00002670 EPI.ExceptionSpecType != EST_None &&
2671 EPI.ExceptionSpecType != EST_DynamicNone &&
2672 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00002673 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2674 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2675 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smithb9d0b762012-07-27 04:22:15 +00002676 assert(EPI.ExceptionSpecType != EST_Unevaluated &&
2677 "instantiating implicitly-declared special member");
Richard Smith13bffc52012-04-19 00:08:28 +00002678
Richard Smithe6975e92012-04-17 00:58:00 +00002679 // Mark the function has having an uninstantiated exception specification.
2680 const FunctionProtoType *NewProto
2681 = New->getType()->getAs<FunctionProtoType>();
2682 assert(NewProto && "Template instantiation without function prototype?");
2683 EPI = NewProto->getExtProtoInfo();
2684 EPI.ExceptionSpecType = EST_Uninstantiated;
2685 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00002686 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Richard Smithe6975e92012-04-17 00:58:00 +00002687 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002688 ArrayRef<QualType>(NewProto->arg_type_begin(),
2689 NewProto->getNumArgs()),
Richard Smithe6975e92012-04-17 00:58:00 +00002690 EPI));
2691 } else {
2692 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2693 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002694 }
2695
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002696 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00002697 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002698 Tmpl->isDefined(Definition);
2699
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002700 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2701 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002702
Douglas Gregore53060f2009-06-25 22:08:12 +00002703 return false;
2704}
2705
Douglas Gregor5545e162009-03-24 00:38:23 +00002706/// \brief Initializes common fields of an instantiated method
2707/// declaration (New) from the corresponding fields of its template
2708/// (Tmpl).
2709///
2710/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002711bool
2712TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002713 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002714 if (InitFunctionInstantiation(New, Tmpl))
2715 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Douglas Gregor5545e162009-03-24 00:38:23 +00002717 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002718 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002719 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002720
2721 // FIXME: attributes
2722 // FIXME: New needs a pointer to Tmpl
2723 return false;
2724}
Douglas Gregora58861f2009-05-13 20:28:22 +00002725
2726/// \brief Instantiate the definition of the given function from its
2727/// template.
2728///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002729/// \param PointOfInstantiation the point at which the instantiation was
2730/// required. Note that this is not precisely a "point of instantiation"
2731/// for the function, but it's close.
2732///
Douglas Gregora58861f2009-05-13 20:28:22 +00002733/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002734/// function template specialization or member function of a class template
2735/// specialization.
2736///
2737/// \param Recursive if true, recursively instantiates any functions that
2738/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002739///
2740/// \param DefinitionRequired if true, then we are performing an explicit
2741/// instantiation where the body of the function is required. Complain if
2742/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002743void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002744 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002745 bool Recursive,
2746 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002747 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002748 return;
2749
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002750 // Never instantiate an explicit specialization except if it is a class scope
2751 // explicit specialization.
2752 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2753 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002754 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002755
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002756 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002757 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00002758 assert(PatternDecl && "instantiating a non-template");
2759
2760 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2761 assert(PatternDecl && "template definition is not a template");
2762 if (!Pattern) {
2763 // Try to find a defaulted definition
2764 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00002765 }
Sean Huntf996e052011-05-27 20:00:14 +00002766 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002767
Francois Pichet8387e2a2011-04-22 22:18:13 +00002768 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00002769 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00002770 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002771 PendingInstantiations.push_back(
2772 std::make_pair(Function, PointOfInstantiation));
2773 return;
2774 }
2775
2776 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002777 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00002778 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00002779 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002780 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002781 Pattern = PatternDecl->getBody(PatternDecl);
2782 }
2783
Sean Huntf996e052011-05-27 20:00:14 +00002784 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002785 if (DefinitionRequired) {
2786 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002787 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002788 diag::err_explicit_instantiation_undefined_func_template)
2789 << Function->getPrimaryTemplate();
2790 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002791 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002792 diag::err_explicit_instantiation_undefined_member)
2793 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002794
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002795 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002796 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002797 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002798 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002799 } else if (Function->getTemplateSpecializationKind()
2800 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002801 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002802 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002803 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002804
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002805 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002806 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002807
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002808 // C++0x [temp.explicit]p9:
2809 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002810 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002811 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002812 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002813 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002814 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002815 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Richard Smithd4497dd2013-01-25 00:08:28 +00002817 if (PatternDecl->isInlined())
2818 Function->setImplicitlyInline();
2819
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002820 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2821 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002822 return;
2823
Abramo Bagnarae9946242011-11-18 08:08:52 +00002824 // Copy the inner loc start from the pattern.
2825 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2826
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002827 // If we're performing recursive template instantiation, create our own
2828 // queue of pending implicit instantiations that we will instantiate later,
2829 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002830 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002831 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002832 if (Recursive) {
2833 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002834 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002835 }
Mike Stump1eb44332009-09-09 15:08:12 +00002836
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002837 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002838 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002839
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002840 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002841 // recorded, unless we're actually a member function within a local
2842 // class, in which case we need to merge our results with the parent
2843 // scope (of the enclosing function).
2844 bool MergeWithParentScope = false;
2845 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2846 MergeWithParentScope = Rec->isLocalClass();
2847
2848 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002849
Richard Smith1d28caf2012-12-11 01:14:52 +00002850 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00002851 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00002852 else {
2853 ActOnStartOfFunctionDef(0, Function);
2854
2855 // Enter the scope of this instantiation. We don't use
2856 // PushDeclContext because we don't have a scope.
2857 Sema::ContextRAII savedContext(*this, Function);
2858
2859 MultiLevelTemplateArgumentList TemplateArgs =
2860 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2861
2862 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2863 TemplateArgs);
2864
Sean Huntcd10dec2011-05-23 23:14:04 +00002865 // If this is a constructor, instantiate the member initializers.
2866 if (const CXXConstructorDecl *Ctor =
2867 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2868 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2869 TemplateArgs);
2870 }
2871
2872 // Instantiate the function body.
2873 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2874
2875 if (Body.isInvalid())
2876 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002877
Sean Huntcd10dec2011-05-23 23:14:04 +00002878 ActOnFinishFunctionBody(Function, Body.get(),
2879 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00002880
2881 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2882
2883 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00002884 }
2885
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002886 DeclGroupRef DG(Function);
2887 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Douglas Gregor60406be2010-01-16 22:29:39 +00002889 // This class may have local implicit instantiations that need to be
2890 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002891 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002892 Scope.Exit();
2893
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002894 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002895 // Define any pending vtables.
2896 DefineUsedVTables();
2897
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002898 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002899 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002900 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002901
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002902 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00002903 assert(VTableUses.empty() &&
2904 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002905 VTableUses.swap(SavedVTableUses);
2906
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002907 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00002908 assert(PendingInstantiations.empty() &&
2909 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00002910 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002911 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002912}
2913
2914/// \brief Instantiate the definition of the given variable from its
2915/// template.
2916///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002917/// \param PointOfInstantiation the point at which the instantiation was
2918/// required. Note that this is not precisely a "point of instantiation"
2919/// for the function, but it's close.
2920///
2921/// \param Var the already-instantiated declaration of a static member
2922/// variable of a class template specialization.
2923///
2924/// \param Recursive if true, recursively instantiates any functions that
2925/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002926///
2927/// \param DefinitionRequired if true, then we are performing an explicit
2928/// instantiation where an out-of-line definition of the member variable
2929/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002930void Sema::InstantiateStaticDataMemberDefinition(
2931 SourceLocation PointOfInstantiation,
2932 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002933 bool Recursive,
2934 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002935 if (Var->isInvalidDecl())
2936 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Douglas Gregor7caa6822009-07-24 20:34:43 +00002938 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002939 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002940 assert(Def && "This data member was not instantiated from a template?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002941 assert(Def->isStaticDataMember() && "Not a static data member?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002942 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Douglas Gregor0d035142009-10-27 18:42:08 +00002944 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002945 // We did not find an out-of-line definition of this static data member,
2946 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002947 // instantiate this definition (or provide a specialization for it) in
2948 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002949 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002950 Def = Var->getInstantiatedFromStaticDataMember();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002951 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002952 diag::err_explicit_instantiation_undefined_member)
2953 << 2 << Var->getDeclName() << Var->getDeclContext();
2954 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002955 } else if (Var->getTemplateSpecializationKind()
2956 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002957 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002958 std::make_pair(Var, PointOfInstantiation));
2959 }
2960
Douglas Gregor7caa6822009-07-24 20:34:43 +00002961 return;
2962 }
2963
Rafael Espindola234fe652012-03-05 10:54:55 +00002964 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
2965
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002966 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00002967 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002968 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002969
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002970 // C++0x [temp.explicit]p9:
2971 // Except for inline functions, other explicit instantiation declarations
2972 // have the effect of suppressing the implicit instantiation of the entity
2973 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00002974 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002975 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00002977 // Make sure to pass the instantiated variable to the consumer at the end.
2978 struct PassToConsumerRAII {
2979 ASTConsumer &Consumer;
2980 VarDecl *Var;
2981
2982 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
2983 : Consumer(Consumer), Var(Var) { }
2984
2985 ~PassToConsumerRAII() {
2986 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
2987 }
2988 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00002989
Douglas Gregorf15748a2011-06-03 03:35:07 +00002990 // If we already have a definition, we're done.
Nick Lewycky95e38722012-04-04 02:38:36 +00002991 if (VarDecl *Def = Var->getDefinition()) {
2992 // We may be explicitly instantiating something we've already implicitly
2993 // instantiated.
2994 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
2995 PointOfInstantiation);
Douglas Gregorf15748a2011-06-03 03:35:07 +00002996 return;
Nick Lewycky95e38722012-04-04 02:38:36 +00002997 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00002998
Douglas Gregor7caa6822009-07-24 20:34:43 +00002999 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3000 if (Inst)
3001 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Douglas Gregor7caa6822009-07-24 20:34:43 +00003003 // If we're performing recursive template instantiation, create our own
3004 // queue of pending implicit instantiations that we will instantiate later,
3005 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003006 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003007 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003008 if (Recursive) {
3009 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003010 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003011 }
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Douglas Gregor7caa6822009-07-24 20:34:43 +00003013 // Enter the scope of this instantiation. We don't use
3014 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00003015 ContextRAII previousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003016 LocalInstantiationScope Local(*this);
3017
Douglas Gregor1028c9f2009-10-14 21:29:40 +00003018 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00003019 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00003020 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00003021
3022 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003023
3024 if (Var) {
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003025 PassToConsumerRAII.Var = Var;
Douglas Gregor583f33b2009-10-15 18:07:02 +00003026 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
3027 assert(MSInfo && "Missing member specialization information?");
3028 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
3029 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003030 }
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003031 Local.Exit();
3032
Douglas Gregor7caa6822009-07-24 20:34:43 +00003033 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003034 // Define any newly required vtables.
3035 DefineUsedVTables();
3036
Douglas Gregor7caa6822009-07-24 20:34:43 +00003037 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003038 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003039 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Nick Lewycky81559102011-05-31 07:58:42 +00003041 // Restore the set of pending vtables.
3042 assert(VTableUses.empty() &&
3043 "VTableUses should be empty before it is discarded, "
3044 "while instantiating static data member.");
3045 VTableUses.swap(SavedVTableUses);
3046
Douglas Gregor7caa6822009-07-24 20:34:43 +00003047 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003048 assert(PendingInstantiations.empty() &&
3049 "PendingInstantiations should be empty before it is discarded, "
3050 "while instantiating static data member.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003051 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003052 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003053}
Douglas Gregor815215d2009-05-27 05:35:12 +00003054
Anders Carlsson09025312009-08-29 05:16:22 +00003055void
3056Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3057 const CXXConstructorDecl *Tmpl,
3058 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Richard Trieu90ab75b2011-09-09 03:18:59 +00003060 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003061 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003062
Anders Carlsson09025312009-08-29 05:16:22 +00003063 // Instantiate all the initializers.
3064 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003065 InitsEnd = Tmpl->init_end();
3066 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003067 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003068
Chandler Carruth030ef472010-09-03 21:54:20 +00003069 // Only instantiate written initializers, let Sema re-construct implicit
3070 // ones.
3071 if (!Init->isWritten())
3072 continue;
3073
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003074 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003075
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003076 if (Init->isPackExpansion()) {
3077 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003078 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003079 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003080 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3081 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003082 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003083 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003084 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003085 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003086 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003087 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003088 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003089 NumExpansions)) {
3090 AnyErrors = true;
3091 New->setInvalidDecl();
3092 continue;
3093 }
3094 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003095
3096 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003097 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003098 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3099
3100 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003101 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3102 /*CXXDirectInit=*/true);
3103 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003104 AnyErrors = true;
3105 break;
3106 }
3107
3108 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003109 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003110 TemplateArgs,
3111 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003112 New->getDeclName());
3113 if (!BaseTInfo) {
3114 AnyErrors = true;
3115 break;
3116 }
3117
3118 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003119 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003120 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003121 New->getParent(),
3122 SourceLocation());
3123 if (NewInit.isInvalid()) {
3124 AnyErrors = true;
3125 break;
3126 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003127
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003128 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003129 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003130
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003131 continue;
3132 }
3133
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003134 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003135 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3136 /*CXXDirectInit=*/true);
3137 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003138 AnyErrors = true;
3139 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003140 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003141
Anders Carlsson09025312009-08-29 05:16:22 +00003142 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003143 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3144 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3145 TemplateArgs,
3146 Init->getSourceLocation(),
3147 New->getDeclName());
3148 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003149 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003150 New->setInvalidDecl();
3151 continue;
3152 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003153
Douglas Gregor76852c22011-11-01 01:16:03 +00003154 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003155 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003156 New->getParent(), EllipsisLoc);
3157 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003158 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003159 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003160 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003161 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003162 Init->getMemberLocation(),
3163 Init->getMember(),
3164 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003165 if (!Member) {
3166 AnyErrors = true;
3167 New->setInvalidDecl();
3168 continue;
3169 }
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003171 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003172 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003173 } else if (Init->isIndirectMemberInitializer()) {
3174 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003175 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003176 Init->getMemberLocation(),
3177 Init->getIndirectMember(), TemplateArgs));
3178
Douglas Gregorb7107222011-03-04 19:46:35 +00003179 if (!IndirectMember) {
3180 AnyErrors = true;
3181 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003182 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003183 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003184
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003185 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003186 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003187 }
3188
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003189 if (NewInit.isInvalid()) {
3190 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003191 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003192 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003193 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003194 }
3195 }
Mike Stump1eb44332009-09-09 15:08:12 +00003196
Anders Carlsson09025312009-08-29 05:16:22 +00003197 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003198 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003199 /*FIXME: ColonLoc */
3200 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003201 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003202 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003203}
3204
John McCall52a575a2009-08-29 08:11:13 +00003205// TODO: this could be templated if the various decl types used the
3206// same method name.
3207static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3208 ClassTemplateDecl *Instance) {
3209 Pattern = Pattern->getCanonicalDecl();
3210
3211 do {
3212 Instance = Instance->getCanonicalDecl();
3213 if (Pattern == Instance) return true;
3214 Instance = Instance->getInstantiatedFromMemberTemplate();
3215 } while (Instance);
3216
3217 return false;
3218}
3219
Douglas Gregor0d696532009-09-28 06:34:35 +00003220static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3221 FunctionTemplateDecl *Instance) {
3222 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003223
Douglas Gregor0d696532009-09-28 06:34:35 +00003224 do {
3225 Instance = Instance->getCanonicalDecl();
3226 if (Pattern == Instance) return true;
3227 Instance = Instance->getInstantiatedFromMemberTemplate();
3228 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003229
Douglas Gregor0d696532009-09-28 06:34:35 +00003230 return false;
3231}
3232
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003233static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003234isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3235 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003236 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003237 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3238 do {
3239 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3240 Instance->getCanonicalDecl());
3241 if (Pattern == Instance)
3242 return true;
3243 Instance = Instance->getInstantiatedFromMember();
3244 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003245
Douglas Gregored9c0f92009-10-29 00:04:11 +00003246 return false;
3247}
3248
John McCall52a575a2009-08-29 08:11:13 +00003249static bool isInstantiationOf(CXXRecordDecl *Pattern,
3250 CXXRecordDecl *Instance) {
3251 Pattern = Pattern->getCanonicalDecl();
3252
3253 do {
3254 Instance = Instance->getCanonicalDecl();
3255 if (Pattern == Instance) return true;
3256 Instance = Instance->getInstantiatedFromMemberClass();
3257 } while (Instance);
3258
3259 return false;
3260}
3261
3262static bool isInstantiationOf(FunctionDecl *Pattern,
3263 FunctionDecl *Instance) {
3264 Pattern = Pattern->getCanonicalDecl();
3265
3266 do {
3267 Instance = Instance->getCanonicalDecl();
3268 if (Pattern == Instance) return true;
3269 Instance = Instance->getInstantiatedFromMemberFunction();
3270 } while (Instance);
3271
3272 return false;
3273}
3274
3275static bool isInstantiationOf(EnumDecl *Pattern,
3276 EnumDecl *Instance) {
3277 Pattern = Pattern->getCanonicalDecl();
3278
3279 do {
3280 Instance = Instance->getCanonicalDecl();
3281 if (Pattern == Instance) return true;
3282 Instance = Instance->getInstantiatedFromMemberEnum();
3283 } while (Instance);
3284
3285 return false;
3286}
3287
John McCalled976492009-12-04 22:46:56 +00003288static bool isInstantiationOf(UsingShadowDecl *Pattern,
3289 UsingShadowDecl *Instance,
3290 ASTContext &C) {
3291 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3292}
3293
3294static bool isInstantiationOf(UsingDecl *Pattern,
3295 UsingDecl *Instance,
3296 ASTContext &C) {
3297 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3298}
3299
John McCall7ba107a2009-11-18 02:36:19 +00003300static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3301 UsingDecl *Instance,
3302 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003303 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003304}
3305
3306static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003307 UsingDecl *Instance,
3308 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003309 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003310}
3311
John McCall52a575a2009-08-29 08:11:13 +00003312static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3313 VarDecl *Instance) {
3314 assert(Instance->isStaticDataMember());
3315
3316 Pattern = Pattern->getCanonicalDecl();
3317
3318 do {
3319 Instance = Instance->getCanonicalDecl();
3320 if (Pattern == Instance) return true;
3321 Instance = Instance->getInstantiatedFromStaticDataMember();
3322 } while (Instance);
3323
3324 return false;
3325}
3326
John McCalled976492009-12-04 22:46:56 +00003327// Other is the prospective instantiation
3328// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003329static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003330 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003331 if (UnresolvedUsingTypenameDecl *UUD
3332 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3333 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3334 return isInstantiationOf(UUD, UD, Ctx);
3335 }
3336 }
3337
3338 if (UnresolvedUsingValueDecl *UUD
3339 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003340 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3341 return isInstantiationOf(UUD, UD, Ctx);
3342 }
3343 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003344
Anders Carlsson0d8df782009-08-29 19:37:28 +00003345 return false;
3346 }
Mike Stump1eb44332009-09-09 15:08:12 +00003347
John McCall52a575a2009-08-29 08:11:13 +00003348 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3349 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003350
John McCall52a575a2009-08-29 08:11:13 +00003351 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3352 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003353
John McCall52a575a2009-08-29 08:11:13 +00003354 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3355 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003356
Douglas Gregor7caa6822009-07-24 20:34:43 +00003357 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003358 if (Var->isStaticDataMember())
3359 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3360
3361 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3362 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003363
Douglas Gregor0d696532009-09-28 06:34:35 +00003364 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3365 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3366
Douglas Gregored9c0f92009-10-29 00:04:11 +00003367 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3368 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3369 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3370 PartialSpec);
3371
Anders Carlssond8b285f2009-09-01 04:26:58 +00003372 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3373 if (!Field->getDeclName()) {
3374 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003375 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003376 cast<FieldDecl>(D);
3377 }
3378 }
Mike Stump1eb44332009-09-09 15:08:12 +00003379
John McCalled976492009-12-04 22:46:56 +00003380 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3381 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3382
3383 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3384 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3385
Douglas Gregor815215d2009-05-27 05:35:12 +00003386 return D->getDeclName() && isa<NamedDecl>(Other) &&
3387 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3388}
3389
3390template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00003391static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00003392 NamedDecl *D,
3393 ForwardIterator first,
3394 ForwardIterator last) {
3395 for (; first != last; ++first)
3396 if (isInstantiationOf(Ctx, D, *first))
3397 return cast<NamedDecl>(*first);
3398
3399 return 0;
3400}
3401
John McCall02cace72009-08-28 07:59:38 +00003402/// \brief Finds the instantiation of the given declaration context
3403/// within the current instantiation.
3404///
3405/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003406DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00003407 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00003408 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003409 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00003410 return cast_or_null<DeclContext>(ID);
3411 } else return DC;
3412}
3413
Douglas Gregored961e72009-05-27 17:54:46 +00003414/// \brief Find the instantiation of the given declaration within the
3415/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00003416///
3417/// This routine is intended to be used when \p D is a declaration
3418/// referenced from within a template, that needs to mapped into the
3419/// corresponding declaration within an instantiation. For example,
3420/// given:
3421///
3422/// \code
3423/// template<typename T>
3424/// struct X {
3425/// enum Kind {
3426/// KnownValue = sizeof(T)
3427/// };
3428///
3429/// bool getKind() const { return KnownValue; }
3430/// };
3431///
3432/// template struct X<int>;
3433/// \endcode
3434///
3435/// In the instantiation of X<int>::getKind(), we need to map the
3436/// EnumConstantDecl for KnownValue (which refers to
James Dennettf198d122012-06-17 03:36:08 +00003437/// X<T>::\<Kind>\::KnownValue) to its instantiation
James Dennettef2b5b32012-06-15 22:23:43 +00003438/// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
Douglas Gregored961e72009-05-27 17:54:46 +00003439/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003440NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00003441 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00003442 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00003443 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00003444 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003445 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3446 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003447 // D is a local of some kind. Look into the map of local
3448 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00003449 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3450 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3451 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003452
Chris Lattner57ad3782011-02-17 20:34:02 +00003453 if (Found) {
3454 if (Decl *FD = Found->dyn_cast<Decl *>())
3455 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003456
Richard Smith9a4db032012-09-12 00:56:43 +00003457 int PackIdx = ArgumentPackSubstitutionIndex;
3458 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00003459 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3460 }
3461
3462 // If we didn't find the decl, then we must have a label decl that hasn't
3463 // been found yet. Lazily instantiate it and return it now.
3464 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003465
Chris Lattner57ad3782011-02-17 20:34:02 +00003466 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3467 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003468
Chris Lattner57ad3782011-02-17 20:34:02 +00003469 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3470 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003471 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003472
Douglas Gregore95b4092009-09-16 18:34:49 +00003473 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3474 if (!Record->isDependentContext())
3475 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003476
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003477 // Determine whether this record is the "templated" declaration describing
3478 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00003479 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003480 if (ClassTemplate)
3481 ClassTemplate = ClassTemplate->getCanonicalDecl();
3482 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3483 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3484 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3485
3486 // Walk the current context to find either the record or an instantiation of
3487 // it.
3488 DeclContext *DC = CurContext;
3489 while (!DC->isFileContext()) {
3490 // If we're performing substitution while we're inside the template
3491 // definition, we'll find our own context. We're done.
3492 if (DC->Equals(Record))
3493 return Record;
3494
3495 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3496 // Check whether we're in the process of instantiating a class template
3497 // specialization of the template we're mapping.
3498 if (ClassTemplateSpecializationDecl *InstSpec
3499 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3500 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3501 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3502 return InstRecord;
3503 }
3504
3505 // Check whether we're in the process of instantiating a member class.
3506 if (isInstantiationOf(Record, InstRecord))
3507 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00003508 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003509
3510
3511 // Move to the outer template scope.
3512 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3513 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3514 DC = FD->getLexicalDeclContext();
3515 continue;
3516 }
John McCall52a575a2009-08-29 08:11:13 +00003517 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003518
3519 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00003520 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003521
Douglas Gregore95b4092009-09-16 18:34:49 +00003522 // Fall through to deal with other dependent record types (e.g.,
3523 // anonymous unions in class templates).
3524 }
John McCall52a575a2009-08-29 08:11:13 +00003525
Douglas Gregore95b4092009-09-16 18:34:49 +00003526 if (!ParentDC->isDependentContext())
3527 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003528
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003529 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003530 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003531 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Douglas Gregor815215d2009-05-27 05:35:12 +00003533 if (ParentDC != D->getDeclContext()) {
3534 // We performed some kind of instantiation in the parent context,
3535 // so now we need to look into the instantiated parent context to
3536 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003537
John McCall3cb0ebd2010-03-10 03:28:59 +00003538 // If our context used to be dependent, we may need to instantiate
3539 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003540 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003541 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003542 if (!Spec->isDependentContext()) {
3543 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003544 const RecordType *Tag = T->getAs<RecordType>();
3545 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003546 if (Tag->isBeingDefined())
3547 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003548 if (!Tag->isBeingDefined() &&
3549 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3550 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003551
3552 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003553 }
3554 }
3555
Douglas Gregor815215d2009-05-27 05:35:12 +00003556 NamedDecl *Result = 0;
3557 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003558 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00003559 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003560 } else {
3561 // Since we don't have a name for the entity we're looking for,
3562 // our only option is to walk through all of the declarations to
3563 // find that name. This will occur in a few cases:
3564 //
3565 // - anonymous struct/union within a template
3566 // - unnamed class/struct/union/enum within a template
3567 //
3568 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003569 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003570 ParentDC->decls_begin(),
3571 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003572 }
Mike Stump1eb44332009-09-09 15:08:12 +00003573
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003574 if (!Result) {
3575 if (isa<UsingShadowDecl>(D)) {
3576 // UsingShadowDecls can instantiate to nothing because of using hiding.
3577 } else if (Diags.hasErrorOccurred()) {
3578 // We've already complained about something, so most likely this
3579 // declaration failed to instantiate. There's no point in complaining
3580 // further, since this is normal in invalid code.
3581 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003582 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003583 // instantiated, and we haven't gotten around to instantiating this
3584 // member yet. This can happen when the code uses forward declarations
3585 // of member classes, and introduces ordering dependencies via
3586 // template instantiation.
3587 Diag(Loc, diag::err_member_not_yet_instantiated)
3588 << D->getDeclName()
3589 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3590 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00003591 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3592 // This enumeration constant was found when the template was defined,
3593 // but can't be found in the instantiation. This can happen if an
3594 // unscoped enumeration member is explicitly specialized.
3595 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3596 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3597 TemplateArgs));
3598 assert(Spec->getTemplateSpecializationKind() ==
3599 TSK_ExplicitSpecialization);
3600 Diag(Loc, diag::err_enumerator_does_not_exist)
3601 << D->getDeclName()
3602 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3603 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3604 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003605 } else {
3606 // We should have found something, but didn't.
3607 llvm_unreachable("Unable to find instantiation of declaration!");
3608 }
3609 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003610
Douglas Gregor815215d2009-05-27 05:35:12 +00003611 D = Result;
3612 }
3613
Douglas Gregor815215d2009-05-27 05:35:12 +00003614 return D;
3615}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003616
Mike Stump1eb44332009-09-09 15:08:12 +00003617/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003618/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00003619void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003620 // Load pending instantiations from the external source.
3621 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00003622 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003623 ExternalSource->ReadPendingInstantiations(Pending);
3624 PendingInstantiations.insert(PendingInstantiations.begin(),
3625 Pending.begin(), Pending.end());
3626 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003627
Douglas Gregor60406be2010-01-16 22:29:39 +00003628 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003629 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003630 PendingImplicitInstantiation Inst;
3631
3632 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003633 Inst = PendingInstantiations.front();
3634 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003635 } else {
3636 Inst = PendingLocalImplicitInstantiations.front();
3637 PendingLocalImplicitInstantiations.pop_front();
3638 }
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Douglas Gregor7caa6822009-07-24 20:34:43 +00003640 // Instantiate function definitions
3641 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003642 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3643 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003644 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3645 TSK_ExplicitInstantiationDefinition;
3646 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3647 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003648 continue;
3649 }
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Douglas Gregor7caa6822009-07-24 20:34:43 +00003651 // Instantiate static data member definitions.
3652 VarDecl *Var = cast<VarDecl>(Inst.first);
3653 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003654
Chandler Carruth291b4412010-02-13 10:17:50 +00003655 // Don't try to instantiate declarations if the most recent redeclaration
3656 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003657 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00003658 continue;
3659
3660 // Check if the most recent declaration has changed the specialization kind
3661 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003662 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00003663 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00003664 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00003665 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003666 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003667 continue; // No longer need to instantiate this type.
3668 case TSK_ExplicitInstantiationDefinition:
3669 // We only need an instantiation if the pending instantiation *is* the
3670 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003671 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003672 case TSK_ImplicitInstantiation:
3673 break;
3674 }
3675
John McCallf312b1e2010-08-26 23:41:50 +00003676 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3677 "instantiating static data member "
3678 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Chandler Carruth58e390e2010-08-25 08:27:02 +00003680 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3681 TSK_ExplicitInstantiationDefinition;
3682 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3683 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003684 }
3685}
John McCall0c01d182010-03-24 05:22:00 +00003686
3687void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3688 const MultiLevelTemplateArgumentList &TemplateArgs) {
3689 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3690 E = Pattern->ddiag_end(); I != E; ++I) {
3691 DependentDiagnostic *DD = *I;
3692
3693 switch (DD->getKind()) {
3694 case DependentDiagnostic::Access:
3695 HandleDependentAccessCheck(*DD, TemplateArgs);
3696 break;
3697 }
3698 }
3699}