blob: ce7684c9edbfaf4a7216c7aeaa875fda4055be02 [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 {
Richard Smithcafeb942013-06-07 02:33:37 +0000145 // Allow 'this' within late-parsed attributes.
146 NamedDecl *ND = dyn_cast<NamedDecl>(New);
147 CXXRecordDecl *ThisContext =
148 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
149 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
150 ND && ND->isCXXInstanceMember());
151
Benjamin Kramer5bbc3852012-02-06 11:13:08 +0000152 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
153 *this, TemplateArgs);
Rafael Espindola31c195a2012-05-15 14:09:55 +0000154 if (NewAttr)
155 New->addAttr(NewAttr);
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000156 }
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000157 }
158}
159
Douglas Gregor4f722be2009-03-25 15:45:12 +0000160Decl *
161TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000162 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000163}
164
165Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000166TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
167 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
168 D->getIdentifier());
169 Owner->addDecl(Inst);
170 return Inst;
171}
172
173Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000174TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000175 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000176}
177
John McCall3dbd3d52010-02-16 06:53:13 +0000178Decl *
179TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
180 NamespaceAliasDecl *Inst
181 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
182 D->getNamespaceLoc(),
183 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000184 D->getIdentifier(),
185 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000186 D->getTargetNameLoc(),
187 D->getNamespace());
188 Owner->addDecl(Inst);
189 return Inst;
190}
191
Richard Smith3e4c6c42011-05-05 21:57:07 +0000192Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
193 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000195 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000196 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000197 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000198 DI = SemaRef.SubstType(DI, TemplateArgs,
199 D->getLocation(), D->getDeclName());
200 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000201 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000202 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000203 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000204 } else {
205 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000206 }
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Richard Smithb5b37d12012-10-23 00:32:41 +0000208 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
209 // libstdc++ relies upon this bug in its implementation of common_type.
210 // If we happen to be processing that implementation, fake up the g++ ?:
211 // semantics. See LWG issue 2141 for more information on the bug.
212 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
213 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
214 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
215 DT->isReferenceType() &&
216 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
217 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
218 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
219 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
220 // Fold it to the (non-reference) type which g++ would have produced.
221 DI = SemaRef.Context.getTrivialTypeSourceInfo(
222 DI->getType().getNonReferenceType());
223
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000224 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000225 TypedefNameDecl *Typedef;
226 if (IsTypeAlias)
227 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
228 D->getLocation(), D->getIdentifier(), DI);
229 else
230 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
231 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000232 if (Invalid)
233 Typedef->setInvalidDecl();
234
John McCallcde5a402011-02-01 08:20:08 +0000235 // If the old typedef was the name for linkage purposes of an anonymous
236 // tag decl, re-establish that relationship for the new typedef.
237 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
238 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregorc61361b2013-03-08 22:15:15 +0000239 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCallcde5a402011-02-01 08:20:08 +0000240 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall83972f12013-03-09 00:54:27 +0000241 assert(!newTag->hasNameForLinkage());
Richard Smith162e1c12011-04-15 14:24:37 +0000242 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000243 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000244 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000245
Douglas Gregoref96ee02012-01-14 16:38:05 +0000246 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000247 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
248 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000249 if (!InstPrev)
250 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000251
Rafael Espindola5df37bd2011-12-26 22:42:47 +0000252 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
253
254 // If the typedef types are not identical, reject them.
255 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
256
257 Typedef->setPreviousDeclaration(InstPrevTypedef);
John McCall5126fd02009-12-30 00:31:22 +0000258 }
259
John McCall1d8d1cc2010-08-01 02:01:53 +0000260 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000261
John McCall46460a62010-01-20 21:53:11 +0000262 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000264 return Typedef;
265}
266
Richard Smith162e1c12011-04-15 14:24:37 +0000267Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000268 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
269 Owner->addDecl(Typedef);
270 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000271}
272
273Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000274 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
275 Owner->addDecl(Typedef);
276 return Typedef;
277}
278
279Decl *
280TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
281 // Create a local instantiation scope for this type alias template, which
282 // will contain the instantiations of the template parameters.
283 LocalInstantiationScope Scope(SemaRef);
284
285 TemplateParameterList *TempParams = D->getTemplateParameters();
286 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
287 if (!InstParams)
288 return 0;
289
290 TypeAliasDecl *Pattern = D->getTemplatedDecl();
291
292 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000293 if (Pattern->getPreviousDecl()) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000294 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000295 if (!Found.empty()) {
296 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3e4c6c42011-05-05 21:57:07 +0000297 }
298 }
299
300 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
301 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
302 if (!AliasInst)
303 return 0;
304
305 TypeAliasTemplateDecl *Inst
306 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
307 D->getDeclName(), InstParams, AliasInst);
308 if (PrevAliasTemplate)
309 Inst->setPreviousDeclaration(PrevAliasTemplate);
310
311 Inst->setAccess(D->getAccess());
312
313 if (!PrevAliasTemplate)
314 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000315
Richard Smith3e4c6c42011-05-05 21:57:07 +0000316 Owner->addDecl(Inst);
317
318 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000319}
320
Larisse Voufoef4579c2013-08-06 01:03:05 +0000321// FIXME: Revise for static member templates.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufoef4579c2013-08-06 01:03:05 +0000323 return VisitVarDecl(D, /*ForVarTemplate=*/false);
324}
325
326Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, bool ForVarTemplate) {
327
Douglas Gregor9901c572010-05-21 00:31:19 +0000328 // If this is the variable for an anonymous struct or union,
329 // instantiate the anonymous struct/union type first.
330 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
331 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
332 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
333 return 0;
334
John McCallce3ff2b2009-08-25 22:02:44 +0000335 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000336 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000337 TemplateArgs,
338 D->getTypeSpecStartLoc(),
339 D->getDeclName());
340 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000341 return 0;
342
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000343 if (DI->getType()->isFunctionType()) {
344 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
345 << D->isStaticDataMember() << DI->getType();
346 return 0;
347 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000348
Larisse Voufoef4579c2013-08-06 01:03:05 +0000349 // Build the instantiated declaration.
350 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000351 D->getLocation(), D->getIdentifier(),
Larisse Voufoef4579c2013-08-06 01:03:05 +0000352 DI->getType(), DI, D->getStorageClass());
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000354 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000355 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000356 SemaRef.inferObjCARCLifetime(Var))
357 Var->setInvalidDecl();
358
Larisse Voufoef4579c2013-08-06 01:03:05 +0000359 // Substitute the nested name specifier, if any.
360 if (SubstQualifier(D, Var))
361 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Larisse Voufoef4579c2013-08-06 01:03:05 +0000363 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
364 StartingScope, ForVarTemplate);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000365 return Var;
366}
367
Abramo Bagnara6206d532010-06-05 05:09:32 +0000368Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
369 AccessSpecDecl* AD
370 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
371 D->getAccessSpecifierLoc(), D->getColonLoc());
372 Owner->addHiddenDecl(AD);
373 return AD;
374}
375
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000376Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
377 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000378 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000379 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000380 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000381 DI = SemaRef.SubstType(DI, TemplateArgs,
382 D->getLocation(), D->getDeclName());
383 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000384 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000385 Invalid = true;
386 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000387 // C++ [temp.arg.type]p3:
388 // If a declaration acquires a function type through a type
389 // dependent on a template-parameter and this causes a
390 // declaration that does not use the syntactic form of a
391 // function declarator to have function type, the program is
392 // ill-formed.
393 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000394 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000395 Invalid = true;
396 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000397 } else {
398 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000399 }
400
401 Expr *BitWidth = D->getBitWidth();
402 if (Invalid)
403 BitWidth = 0;
404 else if (BitWidth) {
Richard Smithf6702a32011-12-20 02:08:33 +0000405 // The bit-width expression is a constant expression.
406 EnterExpressionEvaluationContext Unevaluated(SemaRef,
407 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000408
John McCall60d7b3a2010-08-24 06:29:42 +0000409 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000410 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000411 if (InstantiatedBitWidth.isInvalid()) {
412 Invalid = true;
413 BitWidth = 0;
414 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000415 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000416 }
417
John McCall07fb6be2009-10-22 23:33:21 +0000418 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
419 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000420 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000421 D->getLocation(),
422 D->isMutable(),
423 BitWidth,
Richard Smithca523302012-06-10 03:12:00 +0000424 D->getInClassInitStyle(),
Richard Smith703b6012012-05-23 04:22:22 +0000425 D->getInnerLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000426 D->getAccess(),
427 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000428 if (!Field) {
429 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000430 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000431 }
Mike Stump1eb44332009-09-09 15:08:12 +0000432
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000433 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000434
Richard Smithbe507b62013-02-01 08:12:08 +0000435 if (Field->hasAttrs())
436 SemaRef.CheckAlignasUnderalignment(Field);
437
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000438 if (Invalid)
439 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000441 if (!Field->getDeclName()) {
442 // Keep track of where this decl came from.
443 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000444 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000445 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
446 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000447 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000448 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000449 }
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000451 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000452 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000453 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454
455 return Field;
456}
457
John McCall76da55d2013-04-16 07:28:30 +0000458Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
459 bool Invalid = false;
460 TypeSourceInfo *DI = D->getTypeSourceInfo();
461
462 if (DI->getType()->isVariablyModifiedType()) {
463 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
464 << D->getName();
465 Invalid = true;
466 } else if (DI->getType()->isInstantiationDependentType()) {
467 DI = SemaRef.SubstType(DI, TemplateArgs,
468 D->getLocation(), D->getDeclName());
469 if (!DI) {
470 DI = D->getTypeSourceInfo();
471 Invalid = true;
472 } else if (DI->getType()->isFunctionType()) {
473 // C++ [temp.arg.type]p3:
474 // If a declaration acquires a function type through a type
475 // dependent on a template-parameter and this causes a
476 // declaration that does not use the syntactic form of a
477 // function declarator to have function type, the program is
478 // ill-formed.
479 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
480 << DI->getType();
481 Invalid = true;
482 }
483 } else {
484 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
485 }
486
487 MSPropertyDecl *Property = new (SemaRef.Context)
488 MSPropertyDecl(Owner, D->getLocation(),
489 D->getDeclName(), DI->getType(), DI,
490 D->getLocStart(),
491 D->getGetterId(), D->getSetterId());
492
493 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
494 StartingScope);
495
496 if (Invalid)
497 Property->setInvalidDecl();
498
499 Property->setAccess(D->getAccess());
500 Owner->addDecl(Property);
501
502 return Property;
503}
504
Francois Pichet87c2e122010-11-21 06:08:52 +0000505Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
506 NamedDecl **NamedChain =
507 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
508
509 int i = 0;
510 for (IndirectFieldDecl::chain_iterator PI =
511 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000512 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000513 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000514 TemplateArgs);
515 if (!Next)
516 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000517
Douglas Gregorb7107222011-03-04 19:46:35 +0000518 NamedChain[i++] = Next;
519 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000520
Francois Pichet40e17752010-12-09 10:07:54 +0000521 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000522 IndirectFieldDecl* IndirectField
523 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000524 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000525 NamedChain, D->getChainingSize());
526
527
528 IndirectField->setImplicit(D->isImplicit());
529 IndirectField->setAccess(D->getAccess());
530 Owner->addDecl(IndirectField);
531 return IndirectField;
532}
533
John McCall02cace72009-08-28 07:59:38 +0000534Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000535 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000536 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000537 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000538 TypeSourceInfo *InstTy;
539 // If this is an unsupported friend, don't bother substituting template
540 // arguments into it. The actual type referred to won't be used by any
541 // parts of Clang, and may not be valid for instantiating. Just use the
542 // same info for the instantiated friend.
543 if (D->isUnsupportedFriend()) {
544 InstTy = Ty;
545 } else {
546 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
547 D->getLocation(), DeclarationName());
548 }
549 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000550 return 0;
John McCall02cace72009-08-28 07:59:38 +0000551
Richard Smithd6f80da2012-09-20 01:31:00 +0000552 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000553 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000554 if (!FD)
555 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000556
Douglas Gregor06245bf2010-04-07 17:57:12 +0000557 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000558 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000559 Owner->addDecl(FD);
560 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000561 }
562
Douglas Gregor06245bf2010-04-07 17:57:12 +0000563 NamedDecl *ND = D->getFriendDecl();
564 assert(ND && "friend decl must be a decl or a type!");
565
John McCallaf2094e2010-04-08 09:05:18 +0000566 // All of the Visit implementations for the various potential friend
567 // declarations have to be carefully written to work for friend
568 // objects, with the most important detail being that the target
569 // decl should almost certainly not be placed in Owner.
570 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000571 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000572
John McCall02cace72009-08-28 07:59:38 +0000573 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000574 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000575 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000576 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000577 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000578 Owner->addDecl(FD);
579 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000580}
581
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000582Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
583 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Richard Smithf6702a32011-12-20 02:08:33 +0000585 // The expression in a static assertion is a constant expression.
586 EnterExpressionEvaluationContext Unevaluated(SemaRef,
587 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000588
John McCall60d7b3a2010-08-24 06:29:42 +0000589 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000590 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000591 if (InstantiatedAssertExpr.isInvalid())
592 return 0;
593
Richard Smithe3f470a2012-07-11 22:37:56 +0000594 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000595 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000596 D->getMessage(),
597 D->getRParenLoc(),
598 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000599}
600
601Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000602 EnumDecl *PrevDecl = 0;
603 if (D->getPreviousDecl()) {
604 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
605 D->getPreviousDecl(),
606 TemplateArgs);
607 if (!Prev) return 0;
608 PrevDecl = cast<EnumDecl>(Prev);
609 }
610
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000611 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000612 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000613 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000614 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000615 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000616 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000617 // If we have type source information for the underlying type, it means it
618 // has been explicitly set by the user. Perform substitution on it before
619 // moving on.
620 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000621 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
622 DeclarationName());
623 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000624 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000625 else
626 Enum->setIntegerTypeSourceInfo(NewTI);
627 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000628 assert(!D->getIntegerType()->isDependentType()
629 && "Dependent type without type source info");
630 Enum->setIntegerType(D->getIntegerType());
631 }
632 }
633
John McCall5b629aa2010-10-22 23:36:17 +0000634 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
635
Richard Smithf1c66b42012-03-14 23:13:10 +0000636 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000637 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000638 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000639 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000640
Richard Smith4ca93d92012-03-26 04:08:46 +0000641 EnumDecl *Def = D->getDefinition();
642 if (Def && Def != D) {
643 // If this is an out-of-line definition of an enum member template, check
644 // that the underlying types match in the instantiation of both
645 // declarations.
646 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
647 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
648 QualType DefnUnderlying =
649 SemaRef.SubstType(TI->getType(), TemplateArgs,
650 UnderlyingLoc, DeclarationName());
651 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
652 DefnUnderlying, Enum);
653 }
654 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000655
Douglas Gregor96084f12010-03-01 19:00:07 +0000656 if (D->getDeclContext()->isFunctionOrMethod())
657 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000658
Richard Smithf1c66b42012-03-14 23:13:10 +0000659 // C++11 [temp.inst]p1: The implicit instantiation of a class template
660 // specialization causes the implicit instantiation of the declarations, but
661 // not the definitions of scoped member enumerations.
662 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000663 // within a block scope, but we treat that much like a member template. Only
664 // instantiate the definition when visiting the definition in that case, since
665 // we will visit all redeclarations.
666 if (!Enum->isScoped() && Def &&
667 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000668 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000669
670 return Enum;
671}
672
673void TemplateDeclInstantiator::InstantiateEnumDefinition(
674 EnumDecl *Enum, EnumDecl *Pattern) {
675 Enum->startDefinition();
676
Richard Smith1af83c42012-03-23 03:33:32 +0000677 // Update the location to refer to the definition.
678 Enum->setLocation(Pattern->getLocation());
679
Chris Lattner5f9e2722011-07-23 10:55:15 +0000680 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000681
682 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000683 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
684 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000685 EC != ECEnd; ++EC) {
686 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000687 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000688 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000689 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000690 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000691 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
John McCallce3ff2b2009-08-25 22:02:44 +0000693 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000694 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000695
696 // Drop the initial value and continue.
697 bool isInvalid = false;
698 if (Value.isInvalid()) {
699 Value = SemaRef.Owned((Expr *)0);
700 isInvalid = true;
701 }
702
Mike Stump1eb44332009-09-09 15:08:12 +0000703 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000704 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
705 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000706 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000707
708 if (isInvalid) {
709 if (EnumConst)
710 EnumConst->setInvalidDecl();
711 Enum->setInvalidDecl();
712 }
713
714 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000715 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000716
John McCall3b85ecf2010-01-23 22:37:59 +0000717 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000718 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000719 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000720 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000721
Richard Smithf1c66b42012-03-14 23:13:10 +0000722 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
723 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000724 // If the enumeration is within a function or method, record the enum
725 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000726 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000727 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000728 }
729 }
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Richard Smithf1c66b42012-03-14 23:13:10 +0000731 // FIXME: Fixup LBraceLoc
732 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
733 Enum->getRBraceLoc(), Enum,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +0000734 Enumerators,
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000735 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000736}
737
Douglas Gregor6477b692009-03-25 15:04:13 +0000738Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000739 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000740}
741
John McCalle29ba202009-08-20 01:44:21 +0000742Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000743 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
744
Douglas Gregor550d9b22009-10-31 17:21:17 +0000745 // Create a local instantiation scope for this class template, which
746 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000747 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000748 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000749 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000750 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000751 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000752
753 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000754
755 // Instantiate the qualifier. We have to do this first in case
756 // we're a friend declaration, because if we are then we need to put
757 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000758 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
759 if (QualifierLoc) {
760 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
761 TemplateArgs);
762 if (!QualifierLoc)
763 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000764 }
765
766 CXXRecordDecl *PrevDecl = 0;
767 ClassTemplateDecl *PrevClassTemplate = 0;
768
Douglas Gregoref96ee02012-01-14 16:38:05 +0000769 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000770 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000771 if (!Found.empty()) {
772 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky37574f52010-11-08 23:29:42 +0000773 if (PrevClassTemplate)
774 PrevDecl = PrevClassTemplate->getTemplatedDecl();
775 }
776 }
777
John McCall93ba8572010-03-25 06:39:04 +0000778 // If this isn't a friend, then it's a member template, in which
779 // case we just want to build the instantiation in the
780 // specialization. If it is a friend, we want to build it in
781 // the appropriate context.
782 DeclContext *DC = Owner;
783 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000784 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000785 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000786 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000787 DC = SemaRef.computeDeclContext(SS);
788 if (!DC) return 0;
789 } else {
790 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
791 Pattern->getDeclContext(),
792 TemplateArgs);
793 }
794
795 // Look for a previous declaration of the template in the owning
796 // context.
797 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
798 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
799 SemaRef.LookupQualifiedName(R, DC);
800
801 if (R.isSingleResult()) {
802 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
803 if (PrevClassTemplate)
804 PrevDecl = PrevClassTemplate->getTemplatedDecl();
805 }
806
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000807 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000808 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000809 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000810 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000811 return 0;
812 }
813
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000814 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000815 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000816 bool Complain = true;
817
818 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
819 // template for struct std::tr1::__detail::_Map_base, where the
820 // template parameters of the friend declaration don't match the
821 // template parameters of the original declaration. In this one
822 // case, we don't complain about the ill-formed friend
823 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000824 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000825 Pattern->getIdentifier()->isStr("_Map_base") &&
826 DC->isNamespace() &&
827 cast<NamespaceDecl>(DC)->getIdentifier() &&
828 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
829 DeclContext *DCParent = DC->getParent();
830 if (DCParent->isNamespace() &&
831 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
832 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
833 DeclContext *DCParent2 = DCParent->getParent();
834 if (DCParent2->isNamespace() &&
835 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
836 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
837 DCParent2->getParent()->isTranslationUnit())
838 Complain = false;
839 }
840 }
841
John McCall93ba8572010-03-25 06:39:04 +0000842 TemplateParameterList *PrevParams
843 = PrevClassTemplate->getTemplateParameters();
844
845 // Make sure the parameter lists match.
846 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000847 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000848 Sema::TPL_TemplateMatch)) {
849 if (Complain)
850 return 0;
851
852 AdoptedPreviousTemplateParams = true;
853 InstParams = PrevParams;
854 }
John McCall93ba8572010-03-25 06:39:04 +0000855
856 // Do some additional validation, then merge default arguments
857 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000858 if (!AdoptedPreviousTemplateParams &&
859 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000860 Sema::TPC_ClassTemplate))
861 return 0;
862 }
863 }
864
John McCalle29ba202009-08-20 01:44:21 +0000865 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000866 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000867 Pattern->getLocStart(), Pattern->getLocation(),
868 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000869 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000870
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000871 if (QualifierLoc)
872 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000873
John McCalle29ba202009-08-20 01:44:21 +0000874 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000875 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
876 D->getIdentifier(), InstParams, RecordInst,
877 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000878 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000879
John McCall93ba8572010-03-25 06:39:04 +0000880 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000881 if (PrevClassTemplate)
882 Inst->setAccess(PrevClassTemplate->getAccess());
883 else
884 Inst->setAccess(D->getAccess());
885
Richard Smith22050f22013-07-17 23:53:16 +0000886 Inst->setObjectOfFriendDecl();
John McCall93ba8572010-03-25 06:39:04 +0000887 // TODO: do we want to track the instantiation progeny of this
888 // friend target decl?
889 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000890 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000891 if (!PrevClassTemplate)
892 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000893 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000894
Douglas Gregorf0510d42009-10-12 23:11:44 +0000895 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000896 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000897 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000898
Douglas Gregor259571e2009-10-30 22:42:42 +0000899 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000900 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000901 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000902 Inst->setLexicalDeclContext(Owner);
903 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000904 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000905 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000906
Abramo Bagnara4c515482011-11-26 13:33:46 +0000907 if (D->isOutOfLine()) {
908 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
909 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
910 }
911
John McCalle29ba202009-08-20 01:44:21 +0000912 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000913
914 if (!PrevClassTemplate) {
915 // Queue up any out-of-line partial specializations of this member
916 // class template; the client will force their instantiation once
917 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000918 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000919 D->getPartialSpecializations(PartialSpecs);
920 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
921 if (PartialSpecs[I]->isOutOfLine())
922 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
923 }
924
John McCalle29ba202009-08-20 01:44:21 +0000925 return Inst;
926}
927
Douglas Gregord60e1052009-08-27 16:57:43 +0000928Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000929TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
930 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000931 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000932
Douglas Gregored9c0f92009-10-29 00:04:11 +0000933 // Lookup the already-instantiated declaration in the instantiation
934 // of the class template and return that.
935 DeclContext::lookup_result Found
936 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000937 if (Found.empty())
Douglas Gregored9c0f92009-10-29 00:04:11 +0000938 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000939
Douglas Gregored9c0f92009-10-29 00:04:11 +0000940 ClassTemplateDecl *InstClassTemplate
David Blaikie3bc93e32012-12-19 00:45:41 +0000941 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregored9c0f92009-10-29 00:04:11 +0000942 if (!InstClassTemplate)
943 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000944
Douglas Gregord65587f2010-11-10 19:44:59 +0000945 if (ClassTemplatePartialSpecializationDecl *Result
946 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
947 return Result;
948
949 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000950}
951
Larisse Voufoef4579c2013-08-06 01:03:05 +0000952Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
953 assert(D->getTemplatedDecl()->isStaticDataMember() &&
954 "Only static data member templates are allowed.");
955 // FIXME: Also only when instantiating a class?
956
957 // Create a local instantiation scope for this variable template, which
958 // will contain the instantiations of the template parameters.
959 LocalInstantiationScope Scope(SemaRef);
960 TemplateParameterList *TempParams = D->getTemplateParameters();
961 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
962 if (!InstParams)
963 return NULL;
964
965 VarDecl *Pattern = D->getTemplatedDecl();
966 VarTemplateDecl *PrevVarTemplate = 0;
967
968 if (Pattern->getPreviousDecl()) {
969 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
970 if (!Found.empty())
971 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
972 }
973
974 // FIXME: This, and ForVarTemplate, is a hack that is probably unnecessary.
975 // We should use a simplified version of VisitVarDecl.
976 VarDecl *VarInst = cast_or_null<VarDecl>(VisitVarDecl(Pattern, /*ForVarTemplate=*/true));
977
978 DeclContext *DC = Owner;
979
980 /* FIXME: This should be handled in VisitVarDecl, as used to produce
981 VarInst above.
982 // Instantiate the qualifier.
983 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
984 if (QualifierLoc) {
985 QualifierLoc =
986 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
987 if (!QualifierLoc)
988 return 0;
989 }
990
991 if (QualifierLoc)
992 VarInst->setQualifierInfo(QualifierLoc);
993 */
994
995 VarTemplateDecl *Inst = VarTemplateDecl::Create(
996 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
997 VarInst, PrevVarTemplate);
998 VarInst->setDescribedVarTemplate(Inst);
999
1000 Inst->setAccess(D->getAccess());
1001 if (!PrevVarTemplate)
1002 Inst->setInstantiatedFromMemberTemplate(D);
1003
1004 if (D->isOutOfLine()) {
1005 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1006 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1007 }
1008
1009 Owner->addDecl(Inst);
1010
1011 if (!PrevVarTemplate) {
1012 // Queue up any out-of-line partial specializations of this member
1013 // variable template; the client will force their instantiation once
1014 // the enclosing class has been instantiated.
1015 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1016 D->getPartialSpecializations(PartialSpecs);
1017 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1018 if (PartialSpecs[I]->isOutOfLine())
1019 OutOfLineVarPartialSpecs.push_back(
1020 std::make_pair(Inst, PartialSpecs[I]));
1021 }
1022
1023 return Inst;
1024}
1025
1026Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1027 VarTemplatePartialSpecializationDecl *D) {
1028 assert(D->isStaticDataMember() &&
1029 "Only static data member templates are allowed.");
1030 // FIXME: Also only when instantiating a class?
1031
1032 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1033
1034 // Lookup the already-instantiated declaration and return that.
1035 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1036 assert(!Found.empty() && "Instantiation found nothing?");
1037
1038 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1039 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1040
1041 if (VarTemplatePartialSpecializationDecl *Result =
1042 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1043 return Result;
1044
1045 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1046}
1047
Douglas Gregor7974c3b2009-10-07 17:21:34 +00001048Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +00001049TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001050 // Create a local instantiation scope for this function template, which
1051 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001052 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +00001053 // itself.
John McCall2a7fb272010-08-25 05:32:35 +00001054 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +00001055
Douglas Gregord60e1052009-08-27 16:57:43 +00001056 TemplateParameterList *TempParams = D->getTemplateParameters();
1057 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +00001058 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +00001059 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001060
Douglas Gregora735b202009-10-13 14:39:41 +00001061 FunctionDecl *Instantiated = 0;
1062 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001063 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +00001064 InstParams));
1065 else
1066 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001067 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +00001068 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001069
Douglas Gregora735b202009-10-13 14:39:41 +00001070 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +00001071 return 0;
1072
Mike Stump1eb44332009-09-09 15:08:12 +00001073 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001074 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001075 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001076 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001077 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001078 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001079 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001080
John McCallb1a56e72010-03-26 23:10:15 +00001081 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1082
John McCalle976ffe2009-12-14 23:19:40 +00001083 // Link the instantiation back to the pattern *unless* this is a
1084 // non-definition friend declaration.
1085 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001086 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001087 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001088
John McCallb1a56e72010-03-26 23:10:15 +00001089 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001090 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001091 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001092 } else if (InstTemplate->getDeclContext()->isRecord() &&
1093 !D->getPreviousDecl()) {
1094 SemaRef.CheckFriendAccess(InstTemplate);
1095 }
John McCallb1a56e72010-03-26 23:10:15 +00001096
Douglas Gregord60e1052009-08-27 16:57:43 +00001097 return InstTemplate;
1098}
1099
Douglas Gregord475b8d2009-03-25 21:17:03 +00001100Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1101 CXXRecordDecl *PrevDecl = 0;
1102 if (D->isInjectedClassName())
1103 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001104 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001105 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001106 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001107 TemplateArgs);
1108 if (!Prev) return 0;
1109 PrevDecl = cast<CXXRecordDecl>(Prev);
1110 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001111
1112 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001113 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001114 D->getLocStart(), D->getLocation(),
1115 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001116
1117 // Substitute the nested name specifier, if any.
1118 if (SubstQualifier(D, Record))
1119 return 0;
1120
Douglas Gregord475b8d2009-03-25 21:17:03 +00001121 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001122 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1123 // the tag decls introduced by friend class declarations don't have an access
1124 // specifier. Remove once this area of the code gets sorted out.
1125 if (D->getAccess() != AS_none)
1126 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001127 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001128 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001129
John McCall02cace72009-08-28 07:59:38 +00001130 // If the original function was part of a friend declaration,
1131 // inherit its namespace state.
Richard Smith22050f22013-07-17 23:53:16 +00001132 if (D->getFriendObjectKind())
1133 Record->setObjectOfFriendDecl();
John McCall02cace72009-08-28 07:59:38 +00001134
Douglas Gregor9901c572010-05-21 00:31:19 +00001135 // Make sure that anonymous structs and unions are recorded.
1136 if (D->isAnonymousStructOrUnion()) {
1137 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001138 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001139 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1140 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001141
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001142 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001143 return Record;
1144}
1145
Douglas Gregor71074fd2012-09-13 21:56:43 +00001146/// \brief Adjust the given function type for an instantiation of the
1147/// given declaration, to cope with modifications to the function's type that
1148/// aren't reflected in the type-source information.
1149///
1150/// \param D The declaration we're instantiating.
1151/// \param TInfo The already-instantiated type.
1152static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1153 FunctionDecl *D,
1154 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001155 const FunctionProtoType *OrigFunc
1156 = D->getType()->castAs<FunctionProtoType>();
1157 const FunctionProtoType *NewFunc
1158 = TInfo->getType()->castAs<FunctionProtoType>();
1159 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1160 return TInfo->getType();
1161
1162 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1163 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1164 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00001165 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001166}
1167
John McCall02cace72009-08-28 07:59:38 +00001168/// Normal class members are of more specific types and therefore
1169/// don't make it here. This function serves two purposes:
1170/// 1) instantiating function templates
1171/// 2) substituting friend declarations
1172/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001173Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001174 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001175 // Check whether there is already a function template specialization for
1176 // this declaration.
1177 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001178 if (FunctionTemplate && !TemplateParams) {
Richard Smithc95d4132013-05-03 23:46:09 +00001179 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001181 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001182 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001183 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001184 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Douglas Gregor127102b2009-06-29 20:59:39 +00001186 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001187 if (SpecFunc)
1188 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001189 }
Mike Stump1eb44332009-09-09 15:08:12 +00001190
John McCallb0cb0222010-03-27 05:57:59 +00001191 bool isFriend;
1192 if (FunctionTemplate)
1193 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1194 else
1195 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1196
Douglas Gregor79c22782010-01-16 20:21:20 +00001197 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001198 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001199 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001200 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001201 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Chris Lattner5f9e2722011-07-23 10:55:15 +00001203 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001204 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001205 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001206 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001207 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001208
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001209 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1210 if (QualifierLoc) {
1211 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1212 TemplateArgs);
1213 if (!QualifierLoc)
1214 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001215 }
1216
John McCall68b6b872010-02-06 01:50:47 +00001217 // If we're instantiating a local function declaration, put the result
1218 // in the owner; otherwise we need to find the instantiated context.
1219 DeclContext *DC;
1220 if (D->getDeclContext()->isFunctionOrMethod())
1221 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001222 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001223 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001224 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001225 DC = SemaRef.computeDeclContext(SS);
1226 if (!DC) return 0;
1227 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001228 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001229 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001230 }
John McCall68b6b872010-02-06 01:50:47 +00001231
John McCall02cace72009-08-28 07:59:38 +00001232 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001233 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001234 D->getNameInfo(), T, TInfo,
Rafael Espindola459ef032013-04-16 02:29:15 +00001235 D->getCanonicalDecl()->getStorageClass(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001236 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001237 D->isConstexpr());
Enea Zaffanellade9ed712013-07-19 18:02:36 +00001238 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCallb6217662010-03-15 10:12:16 +00001239
Richard Smithd4497dd2013-01-25 00:08:28 +00001240 if (D->isInlined())
1241 Function->setImplicitlyInline();
1242
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001243 if (QualifierLoc)
1244 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001245
John McCallb1a56e72010-03-26 23:10:15 +00001246 DeclContext *LexicalDC = Owner;
1247 if (!isFriend && D->isOutOfLine()) {
1248 assert(D->getDeclContext()->isFileContext());
1249 LexicalDC = D->getDeclContext();
1250 }
1251
1252 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Douglas Gregore53060f2009-06-25 22:08:12 +00001254 // Attach the parameters
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001255 for (unsigned P = 0; P < Params.size(); ++P)
1256 if (Params[P])
1257 Params[P]->setOwningFunction(Function);
David Blaikie4278c652011-09-21 18:16:56 +00001258 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001259
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001260 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001261 if (TemplateParams) {
1262 // Our resulting instantiation is actually a function template, since we
1263 // are substituting only the outer template parameters. For example, given
1264 //
1265 // template<typename T>
1266 // struct X {
1267 // template<typename U> friend void f(T, U);
1268 // };
1269 //
1270 // X<int> x;
1271 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001272 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001273 // which means substituting int for T, but leaving "f" as a friend function
1274 // template.
1275 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001276 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001277 Function->getLocation(),
1278 Function->getDeclName(),
1279 TemplateParams, Function);
1280 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001281
1282 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001283
1284 if (isFriend && D->isThisDeclarationADefinition()) {
1285 // TODO: should we remember this connection regardless of whether
1286 // the friend declaration provided a body?
1287 FunctionTemplate->setInstantiatedFromMemberTemplate(
1288 D->getDescribedFunctionTemplate());
1289 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001290 } else if (FunctionTemplate) {
1291 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001292 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001293 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001294 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001295 Innermost.begin(),
1296 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001297 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001298 } else if (isFriend) {
1299 // Note, we need this connection even if the friend doesn't have a body.
1300 // Its body may exist but not have been attached yet due to deferred
1301 // parsing.
1302 // FIXME: It might be cleaner to set this when attaching the body to the
1303 // friend function declaration, however that would require finding all the
1304 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001305 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001306 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001307
Douglas Gregore53060f2009-06-25 22:08:12 +00001308 if (InitFunctionInstantiation(Function, D))
1309 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001310
John McCallaf2094e2010-04-08 09:05:18 +00001311 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001312
John McCall68263142009-11-18 22:49:29 +00001313 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1314 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1315
John McCallaf2094e2010-04-08 09:05:18 +00001316 if (DependentFunctionTemplateSpecializationInfo *Info
1317 = D->getDependentSpecializationInfo()) {
1318 assert(isFriend && "non-friend has dependent specialization info?");
1319
1320 // This needs to be set now for future sanity.
Richard Smith22050f22013-07-17 23:53:16 +00001321 Function->setObjectOfFriendDecl();
John McCallaf2094e2010-04-08 09:05:18 +00001322
1323 // Instantiate the explicit template arguments.
1324 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1325 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001326 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1327 ExplicitArgs, TemplateArgs))
1328 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001329
1330 // Map the candidate templates to their instantiations.
1331 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1332 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1333 Info->getTemplate(I),
1334 TemplateArgs);
1335 if (!Temp) return 0;
1336
1337 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1338 }
1339
1340 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1341 &ExplicitArgs,
1342 Previous))
1343 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001344
John McCallaf2094e2010-04-08 09:05:18 +00001345 isExplicitSpecialization = true;
1346
1347 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001348 // Look only into the namespace where the friend would be declared to
1349 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001350 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001351 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001352
Douglas Gregora735b202009-10-13 14:39:41 +00001353 // In C++, the previous declaration we find might be a tag type
1354 // (class or enum). In this case, the new declaration will hide the
1355 // tag type. Note that this does does not apply if we're declaring a
1356 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001357 if (Previous.isSingleTagDecl())
1358 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001359 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001360
John McCall9f54ad42009-12-10 09:41:52 +00001361 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001362 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001363
John McCall76d32642010-04-24 01:30:58 +00001364 NamedDecl *PrincipalDecl = (TemplateParams
1365 ? cast<NamedDecl>(FunctionTemplate)
1366 : Function);
1367
Douglas Gregora735b202009-10-13 14:39:41 +00001368 // If the original function was part of a friend declaration,
1369 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001370 if (isFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00001371 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001372 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001373
Gabor Greif77535df2010-08-30 22:25:56 +00001374 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001375
Richard Smith53e53512011-10-19 00:54:10 +00001376 // C++98 [temp.friend]p5: When a function is defined in a friend function
1377 // declaration in a class template, the function is defined at each
1378 // instantiation of the class template. The function is defined even if it
1379 // is never used.
1380 // C++11 [temp.friend]p4: When a function is defined in a friend function
1381 // declaration in a class template, the function is instantiated when the
1382 // function is odr-used.
1383 //
1384 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1385 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001386 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001387 SemaRef.Diags.getDiagnosticLevel(
1388 diag::warn_cxx98_compat_friend_redefinition,
1389 Function->getLocation())
1390 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001391 D->isThisDeclarationADefinition()) {
1392 // Check for a function body.
1393 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001394 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001395 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001396 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001397 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001398 diag::warn_cxx98_compat_friend_redefinition :
1399 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001400 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001401 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001402 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001403 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001404 // Check for redefinitions due to other instantiations of this or
1405 // a similar friend function.
1406 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1407 REnd = Function->redecls_end();
1408 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001409 if (*R == Function)
1410 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001411 switch (R->getFriendObjectKind()) {
1412 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001413 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001414 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001415 if (MemberSpecializationInfo *MSInfo
1416 = Function->getMemberSpecializationInfo()) {
1417 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1418 SourceLocation Loc = R->getLocation(); // FIXME
1419 MSInfo->setPointOfInstantiation(Loc);
1420 SemaRef.PendingLocalImplicitInstantiations.push_back(
1421 std::make_pair(Function, Loc));
1422 queuedInstantiation = true;
1423 }
1424 }
1425 }
1426 break;
1427 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001428 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001429 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001430 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001431 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001432 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001433 diag::warn_cxx98_compat_friend_redefinition :
1434 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001435 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001436 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001437 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001438 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001439 break;
1440 }
1441 }
1442 }
1443 }
Douglas Gregora735b202009-10-13 14:39:41 +00001444 }
1445
John McCall76d32642010-04-24 01:30:58 +00001446 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1447 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1448 PrincipalDecl->setNonMemberOperator();
1449
Sean Hunteb88ae52011-05-23 21:07:59 +00001450 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001451 return Function;
1452}
1453
Douglas Gregord60e1052009-08-27 16:57:43 +00001454Decl *
1455TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001456 TemplateParameterList *TemplateParams,
1457 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001458 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001459 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001460 // We are creating a function template specialization from a function
1461 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001462 // specialization for this particular set of template arguments.
Richard Smithc95d4132013-05-03 23:46:09 +00001463 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001465 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001466 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001467 = FunctionTemplate->findSpecialization(Innermost.begin(),
1468 Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001469 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Douglas Gregor6b906862009-08-21 00:16:32 +00001471 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001472 if (SpecFunc)
1473 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001474 }
1475
John McCallb0cb0222010-03-27 05:57:59 +00001476 bool isFriend;
1477 if (FunctionTemplate)
1478 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1479 else
1480 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1481
Douglas Gregor79c22782010-01-16 20:21:20 +00001482 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001483 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001484 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001485 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001486
John McCall4eab39f2010-10-19 02:26:41 +00001487 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001488 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001489 unsigned NumTempParamLists = 0;
1490 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1491 TempParamLists.set_size(NumTempParamLists);
1492 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1493 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1494 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1495 if (!InstParams)
1496 return NULL;
1497 TempParamLists[I] = InstParams;
1498 }
1499 }
1500
Chris Lattner5f9e2722011-07-23 10:55:15 +00001501 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001502 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001503 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001504 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001505 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001506
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001507 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1508 if (QualifierLoc) {
1509 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001510 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001511 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001512 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001513 }
1514
1515 DeclContext *DC = Owner;
1516 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001517 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001518 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001519 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001520 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001521
1522 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1523 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001524 } else {
1525 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1526 D->getDeclContext(),
1527 TemplateArgs);
1528 }
1529 if (!DC) return 0;
1530 }
1531
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001532 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001533 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001534 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001536 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001537 DeclarationNameInfo NameInfo
1538 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001539 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001540 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001541 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001542 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001543 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001544 false, Constructor->isConstexpr());
Richard Smithb5eb3f52013-05-17 02:19:35 +00001545
Richard Smith4841ca52013-04-10 05:48:59 +00001546 // Claim that the instantiation of a constructor or constructor template
1547 // inherits the same constructor that the template does.
Richard Smithb5eb3f52013-05-17 02:19:35 +00001548 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1549 Constructor->getInheritedConstructor())) {
1550 // If we're instantiating a specialization of a function template, our
1551 // "inherited constructor" will actually itself be a function template.
1552 // Instantiate a declaration of it, too.
1553 if (FunctionTemplate) {
1554 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1555 !Inh->getParent()->isDependentContext() &&
1556 "inheriting constructor template in dependent context?");
1557 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1558 Inh);
1559 if (Inst)
1560 return 0;
1561 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1562 LocalInstantiationScope LocalScope(SemaRef);
1563
1564 // Use the same template arguments that we deduced for the inheriting
1565 // constructor. There's no way they could be deduced differently.
1566 MultiLevelTemplateArgumentList InheritedArgs;
1567 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1568 Inh = cast_or_null<CXXConstructorDecl>(
1569 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1570 if (!Inh)
1571 return 0;
1572 }
Richard Smith4841ca52013-04-10 05:48:59 +00001573 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smithb5eb3f52013-05-17 02:19:35 +00001574 }
Douglas Gregor17e32f32009-08-21 22:43:28 +00001575 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001576 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001577 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001578 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001579 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001580 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001581 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001582 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001583 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001584 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001585 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001586 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001587 } else {
Rafael Espindola72fdc892013-04-15 12:38:20 +00001588 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnara25777432010-08-11 22:01:17 +00001589 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001590 StartLoc, NameInfo, T, TInfo,
Rafael Espindola72fdc892013-04-15 12:38:20 +00001591 SC, D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001592 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001593 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001594
Richard Smithd4497dd2013-01-25 00:08:28 +00001595 if (D->isInlined())
1596 Method->setImplicitlyInline();
1597
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001598 if (QualifierLoc)
1599 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001600
Douglas Gregord60e1052009-08-27 16:57:43 +00001601 if (TemplateParams) {
1602 // Our resulting instantiation is actually a function template, since we
1603 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001604 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001605 // template<typename T>
1606 // struct X {
1607 // template<typename U> void f(T, U);
1608 // };
1609 //
1610 // X<int> x;
1611 //
1612 // We are instantiating the member template "f" within X<int>, which means
1613 // substituting int for T, but leaving "f" as a member function template.
1614 // Build the function template itself.
1615 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1616 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001617 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001618 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001619 if (isFriend) {
1620 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001621 FunctionTemplate->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001622 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001623 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001624 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001625 } else if (FunctionTemplate) {
1626 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001627 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001628 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001629 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001630 Innermost.begin(),
1631 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001632 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001633 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001634 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001635 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001636 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001637
Mike Stump1eb44332009-09-09 15:08:12 +00001638 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001639 // out-of-line, the instantiation will have the same lexical
1640 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001641 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001642 if (NumTempParamLists)
1643 Method->setTemplateParameterListsInfo(SemaRef.Context,
1644 NumTempParamLists,
1645 TempParamLists.data());
1646
John McCallb0cb0222010-03-27 05:57:59 +00001647 Method->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001648 Method->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001649 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001650 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Douglas Gregor5545e162009-03-24 00:38:23 +00001652 // Attach the parameters
1653 for (unsigned P = 0; P < Params.size(); ++P)
1654 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001655 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001656
1657 if (InitMethodInstantiation(Method, D))
1658 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001659
Abramo Bagnara25777432010-08-11 22:01:17 +00001660 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1661 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
John McCallb0cb0222010-03-27 05:57:59 +00001663 if (!FunctionTemplate || TemplateParams || isFriend) {
1664 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Douglas Gregordec06662009-08-21 18:42:58 +00001666 // In C++, the previous declaration we find might be a tag type
1667 // (class or enum). In this case, the new declaration will hide the
1668 // tag type. Note that this does does not apply if we're declaring a
1669 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001670 if (Previous.isSingleTagDecl())
1671 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001672 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001673
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001674 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001675 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001676
Douglas Gregor4ba31362009-12-01 17:24:26 +00001677 if (D->isPure())
1678 SemaRef.CheckPureMethod(Method, SourceRange());
1679
John McCall1f2e1a92012-08-10 03:15:35 +00001680 // Propagate access. For a non-friend declaration, the access is
1681 // whatever we're propagating from. For a friend, it should be the
1682 // previous declaration we just found.
1683 if (isFriend && Method->getPreviousDecl())
1684 Method->setAccess(Method->getPreviousDecl()->getAccess());
1685 else
1686 Method->setAccess(D->getAccess());
1687 if (FunctionTemplate)
1688 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001689
Anders Carlsson9eefa222011-01-20 06:52:44 +00001690 SemaRef.CheckOverrideControl(Method);
1691
Eli Friedman3bc45152011-11-15 22:39:08 +00001692 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001693 if (D->isExplicitlyDefaulted())
1694 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001695 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001696 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001697
John McCall1f2e1a92012-08-10 03:15:35 +00001698 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001699 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001700 // do nothing
1701
1702 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001703 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001704 // do nothing
1705
1706 // Otherwise, check access to friends and make them visible.
1707 } else if (isFriend) {
1708 // We only need to re-check access for methods which we didn't
1709 // manage to match during parsing.
1710 if (!D->getPreviousDecl())
1711 SemaRef.CheckFriendAccess(Method);
1712
1713 Record->makeDeclVisibleInContext(Method);
1714
1715 // Otherwise, add the declaration. We don't need to do this for
1716 // class-scope specializations because we'll have matched them with
1717 // the appropriate template.
1718 } else if (!IsClassScopeSpecialization) {
1719 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001720 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001721
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001722 return Method;
1723}
1724
Douglas Gregor615c5d42009-03-24 16:43:20 +00001725Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001726 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001727}
1728
Douglas Gregor03b2b072009-03-24 00:15:49 +00001729Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001730 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001731}
1732
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001733Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001734 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001735}
1736
Eli Friedmanded99792013-06-27 23:21:55 +00001737Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001738 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1739 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001740}
1741
John McCalle29ba202009-08-20 01:44:21 +00001742Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1743 TemplateTypeParmDecl *D) {
1744 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001745 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001746
John McCalle29ba202009-08-20 01:44:21 +00001747 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001748 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1749 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001750 D->getDepth() - TemplateArgs.getNumLevels(),
1751 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001752 D->wasDeclaredWithTypename(),
1753 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001754 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001755
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001756 if (D->hasDefaultArgument())
1757 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1758
1759 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001760 // scope.
1761 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001762
John McCalle29ba202009-08-20 01:44:21 +00001763 return Inst;
1764}
1765
Douglas Gregor33642df2009-10-23 23:25:44 +00001766Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1767 NonTypeTemplateParmDecl *D) {
1768 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001769 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001770 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1771 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001772 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001773 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001774 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001775 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001776
1777 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001778 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001779 // expansion of types. Substitute into each of the expanded types.
1780 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1781 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1782 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1783 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1784 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001785 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001786 D->getDeclName());
1787 if (!NewDI)
1788 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001789
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001790 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1791 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1792 D->getLocation());
1793 if (NewT.isNull())
1794 return 0;
1795 ExpandedParameterPackTypes.push_back(NewT);
1796 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001797
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001798 IsExpandedParameterPack = true;
1799 DI = D->getTypeSourceInfo();
1800 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001801 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001802 // The non-type template parameter pack's type is a pack expansion of types.
1803 // Determine whether we need to expand this parameter pack into separate
1804 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001805 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001806 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001807 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001808 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001809
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001810 // Determine whether the set of unexpanded parameter packs can and should
1811 // be expanded.
1812 bool Expand = true;
1813 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001814 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001815 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001816 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001817 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1818 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001819 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001820 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001821 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001822 NumExpansions))
1823 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001824
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001825 if (Expand) {
1826 for (unsigned I = 0; I != *NumExpansions; ++I) {
1827 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1828 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001829 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001830 D->getDeclName());
1831 if (!NewDI)
1832 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001833
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001834 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1835 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1836 NewDI->getType(),
1837 D->getLocation());
1838 if (NewT.isNull())
1839 return 0;
1840 ExpandedParameterPackTypes.push_back(NewT);
1841 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001842
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001843 // Note that we have an expanded parameter pack. The "type" of this
1844 // expanded parameter pack is the original expansion type, but callers
1845 // will end up using the expanded parameter pack types for type-checking.
1846 IsExpandedParameterPack = true;
1847 DI = D->getTypeSourceInfo();
1848 T = DI->getType();
1849 } else {
1850 // We cannot fully expand the pack expansion now, so substitute into the
1851 // pattern and create a new pack expansion type.
1852 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1853 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001854 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001855 D->getDeclName());
1856 if (!NewPattern)
1857 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001858
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001859 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1860 NumExpansions);
1861 if (!DI)
1862 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001863
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001864 T = DI->getType();
1865 }
1866 } else {
1867 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001868 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001869 D->getLocation(), D->getDeclName());
1870 if (!DI)
1871 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001872
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001873 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001874 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001875 D->getLocation());
1876 if (T.isNull()) {
1877 T = SemaRef.Context.IntTy;
1878 Invalid = true;
1879 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001880 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001881
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001882 NonTypeTemplateParmDecl *Param;
1883 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001884 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001885 D->getInnerLocStart(),
1886 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001887 D->getDepth() - TemplateArgs.getNumLevels(),
1888 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001889 D->getIdentifier(), T,
1890 DI,
1891 ExpandedParameterPackTypes.data(),
1892 ExpandedParameterPackTypes.size(),
1893 ExpandedParameterPackTypesAsWritten.data());
1894 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001895 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001896 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001897 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001898 D->getDepth() - TemplateArgs.getNumLevels(),
1899 D->getPosition(),
1900 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001901 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001902
Douglas Gregor9a299e02011-03-04 17:52:15 +00001903 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001904 if (Invalid)
1905 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001906
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001907 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001908
1909 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001910 // scope.
1911 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001912 return Param;
1913}
1914
Richard Smith6964b3f2012-09-07 02:06:42 +00001915static void collectUnexpandedParameterPacks(
1916 Sema &S,
1917 TemplateParameterList *Params,
1918 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1919 for (TemplateParameterList::const_iterator I = Params->begin(),
1920 E = Params->end(); I != E; ++I) {
1921 if ((*I)->isTemplateParameterPack())
1922 continue;
1923 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1924 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1925 Unexpanded);
1926 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1927 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1928 Unexpanded);
1929 }
1930}
1931
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001932Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001933TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1934 TemplateTemplateParmDecl *D) {
1935 // Instantiate the template parameter list of the template template parameter.
1936 TemplateParameterList *TempParams = D->getTemplateParameters();
1937 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001938 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1939
1940 bool IsExpandedParameterPack = false;
1941
1942 if (D->isExpandedParameterPack()) {
1943 // The template template parameter pack is an already-expanded pack
1944 // expansion of template parameters. Substitute into each of the expanded
1945 // parameters.
1946 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1947 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1948 I != N; ++I) {
1949 LocalInstantiationScope Scope(SemaRef);
1950 TemplateParameterList *Expansion =
1951 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1952 if (!Expansion)
1953 return 0;
1954 ExpandedParams.push_back(Expansion);
1955 }
1956
1957 IsExpandedParameterPack = true;
1958 InstParams = TempParams;
1959 } else if (D->isPackExpansion()) {
1960 // The template template parameter pack expands to a pack of template
1961 // template parameters. Determine whether we need to expand this parameter
1962 // pack into separate parameters.
1963 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1964 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1965 Unexpanded);
1966
1967 // Determine whether the set of unexpanded parameter packs can and should
1968 // be expanded.
1969 bool Expand = true;
1970 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001971 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001972 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1973 TempParams->getSourceRange(),
1974 Unexpanded,
1975 TemplateArgs,
1976 Expand, RetainExpansion,
1977 NumExpansions))
1978 return 0;
1979
1980 if (Expand) {
1981 for (unsigned I = 0; I != *NumExpansions; ++I) {
1982 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1983 LocalInstantiationScope Scope(SemaRef);
1984 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1985 if (!Expansion)
1986 return 0;
1987 ExpandedParams.push_back(Expansion);
1988 }
1989
1990 // Note that we have an expanded parameter pack. The "type" of this
1991 // expanded parameter pack is the original expansion type, but callers
1992 // will end up using the expanded parameter pack types for type-checking.
1993 IsExpandedParameterPack = true;
1994 InstParams = TempParams;
1995 } else {
1996 // We cannot fully expand the pack expansion now, so just substitute
1997 // into the pattern.
1998 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1999
2000 LocalInstantiationScope Scope(SemaRef);
2001 InstParams = SubstTemplateParams(TempParams);
2002 if (!InstParams)
2003 return 0;
2004 }
2005 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00002006 // Perform the actual substitution of template parameters within a new,
2007 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00002008 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00002009 InstParams = SubstTemplateParams(TempParams);
2010 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00002011 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002012 }
2013
Douglas Gregor9106ef72009-11-11 16:58:32 +00002014 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00002015 TemplateTemplateParmDecl *Param;
2016 if (IsExpandedParameterPack)
2017 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2018 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002019 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00002020 D->getPosition(),
2021 D->getIdentifier(), InstParams,
2022 ExpandedParams);
2023 else
2024 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2025 D->getLocation(),
2026 D->getDepth() - TemplateArgs.getNumLevels(),
2027 D->getPosition(),
2028 D->isParameterPack(),
2029 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00002030 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00002031 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002032
2033 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00002034 // scope.
2035 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002036
Douglas Gregor9106ef72009-11-11 16:58:32 +00002037 return Param;
2038}
2039
Douglas Gregor48c32a72009-11-17 06:07:40 +00002040Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00002041 // Using directives are never dependent (and never contain any types or
2042 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002043
Douglas Gregor48c32a72009-11-17 06:07:40 +00002044 UsingDirectiveDecl *Inst
2045 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002046 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00002047 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002048 D->getIdentLocation(),
2049 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00002050 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00002051
2052 // Add the using directive to its declaration context
2053 // only if this is not a function or method.
2054 if (!Owner->isFunctionOrMethod())
2055 Owner->addDecl(Inst);
2056
Douglas Gregor48c32a72009-11-17 06:07:40 +00002057 return Inst;
2058}
2059
John McCalled976492009-12-04 22:46:56 +00002060Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002061
2062 // The nested name specifier may be dependent, for example
2063 // template <typename T> struct t {
2064 // struct s1 { T f1(); };
2065 // struct s2 : s1 { using s1::f1; };
2066 // };
2067 // template struct t<int>;
2068 // Here, in using s1::f1, s1 refers to t<T>::s1;
2069 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002070 NestedNameSpecifierLoc QualifierLoc
2071 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2072 TemplateArgs);
2073 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002074 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002075
2076 // The name info is non-dependent, so no transformation
2077 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002078 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002079
John McCall9f54ad42009-12-10 09:41:52 +00002080 // We only need to do redeclaration lookups if we're in a class
2081 // scope (in fact, it's not really even possible in non-class
2082 // scopes).
2083 bool CheckRedeclaration = Owner->isRecord();
2084
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002085 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2086 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002087
John McCalled976492009-12-04 22:46:56 +00002088 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002089 D->getUsingLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002090 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002091 NameInfo,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002092 D->hasTypename());
John McCalled976492009-12-04 22:46:56 +00002093
Douglas Gregor5149f372011-02-25 15:54:31 +00002094 CXXScopeSpec SS;
2095 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002096 if (CheckRedeclaration) {
2097 Prev.setHideTags(false);
2098 SemaRef.LookupQualifiedName(Prev, Owner);
2099
2100 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002101 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2102 D->hasTypename(), SS,
John McCall9f54ad42009-12-10 09:41:52 +00002103 D->getLocation(), Prev))
2104 NewUD->setInvalidDecl();
2105
2106 }
2107
2108 if (!NewUD->isInvalidDecl() &&
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002109 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCalled976492009-12-04 22:46:56 +00002110 D->getLocation()))
2111 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002112
John McCalled976492009-12-04 22:46:56 +00002113 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2114 NewUD->setAccess(D->getAccess());
2115 Owner->addDecl(NewUD);
2116
John McCall9f54ad42009-12-10 09:41:52 +00002117 // Don't process the shadow decls for an invalid decl.
2118 if (NewUD->isInvalidDecl())
2119 return NewUD;
2120
Richard Smithc5a89a12012-04-02 01:30:27 +00002121 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2122 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2123 NewUD->setInvalidDecl();
2124 return NewUD;
2125 }
2126
John McCall323c3102009-12-22 22:26:37 +00002127 bool isFunctionScope = Owner->isFunctionOrMethod();
2128
John McCall9f54ad42009-12-10 09:41:52 +00002129 // Process the shadow decls.
2130 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2131 I != E; ++I) {
2132 UsingShadowDecl *Shadow = *I;
2133 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002134 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2135 Shadow->getLocation(),
2136 Shadow->getTargetDecl(),
2137 TemplateArgs));
2138 if (!InstTarget)
2139 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002140
2141 if (CheckRedeclaration &&
2142 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2143 continue;
2144
2145 UsingShadowDecl *InstShadow
2146 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2147 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002148
2149 if (isFunctionScope)
2150 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002151 }
John McCalled976492009-12-04 22:46:56 +00002152
2153 return NewUD;
2154}
2155
2156Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002157 // Ignore these; we handle them in bulk when processing the UsingDecl.
2158 return 0;
John McCalled976492009-12-04 22:46:56 +00002159}
2160
John McCall7ba107a2009-11-18 02:36:19 +00002161Decl * TemplateDeclInstantiator
2162 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002163 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002164 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002165 TemplateArgs);
2166 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002167 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002169 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002170 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002172 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002173 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002174 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002175 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002176 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002177 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002178 /*instantiation*/ true,
2179 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002180 if (UD)
John McCalled976492009-12-04 22:46:56 +00002181 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2182
John McCall7ba107a2009-11-18 02:36:19 +00002183 return UD;
2184}
2185
2186Decl * TemplateDeclInstantiator
2187 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002188 NestedNameSpecifierLoc QualifierLoc
2189 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2190 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002191 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002192
John McCall7ba107a2009-11-18 02:36:19 +00002193 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002194 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002195
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002196 DeclarationNameInfo NameInfo
2197 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2198
John McCall7ba107a2009-11-18 02:36:19 +00002199 NamedDecl *UD =
2200 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002201 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002202 /*instantiation*/ true,
2203 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002204 if (UD)
John McCalled976492009-12-04 22:46:56 +00002205 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2206
Anders Carlsson0d8df782009-08-29 19:37:28 +00002207 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002208}
2209
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002210
2211Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2212 ClassScopeFunctionSpecializationDecl *Decl) {
2213 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002214 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2215 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002216
2217 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2218 Sema::ForRedeclaration);
2219
Nico Weber6b020092012-06-25 17:21:05 +00002220 TemplateArgumentListInfo TemplateArgs;
2221 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2222 if (Decl->hasExplicitTemplateArgs()) {
2223 TemplateArgs = Decl->templateArgs();
2224 TemplateArgsPtr = &TemplateArgs;
2225 }
2226
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002227 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002228 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2229 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002230 NewFD->setInvalidDecl();
2231 return NewFD;
2232 }
2233
2234 // Associate the specialization with the pattern.
2235 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2236 assert(Specialization && "Class scope Specialization is null");
2237 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2238
2239 return NewFD;
2240}
2241
Alexey Bataevc6400582013-03-22 06:34:35 +00002242Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2243 OMPThreadPrivateDecl *D) {
Alexey Bataev6af701f2013-05-13 04:18:18 +00002244 SmallVector<Expr *, 5> Vars;
2245 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2246 E = D->varlist_end();
Alexey Bataevc6400582013-03-22 06:34:35 +00002247 I != E; ++I) {
2248 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2249 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6af701f2013-05-13 04:18:18 +00002250 Vars.push_back(Var);
Alexey Bataevc6400582013-03-22 06:34:35 +00002251 }
2252
2253 OMPThreadPrivateDecl *TD =
2254 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2255
2256 return TD;
2257}
2258
Eli Friedmanded99792013-06-27 23:21:55 +00002259Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2260 return VisitFunctionDecl(D, 0);
2261}
2262
2263Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2264 return VisitCXXMethodDecl(D, 0);
2265}
2266
2267Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2268 llvm_unreachable("There are only CXXRecordDecls in C++");
2269}
2270
2271Decl *
2272TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2273 ClassTemplateSpecializationDecl *D) {
2274 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2275 "inside templates");
2276}
2277
Larisse Voufoef4579c2013-08-06 01:03:05 +00002278Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2279 VarTemplateSpecializationDecl *D) {
2280
2281 TemplateArgumentListInfo VarTemplateArgsInfo;
2282 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2283 assert(VarTemplate &&
2284 "A template specialization without specialized template?");
2285
2286 // Substitute the current template arguments.
2287 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2288 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2289 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2290
2291 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2292 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2293 return 0;
2294
2295 // Check that the template argument list is well-formed for this template.
2296 SmallVector<TemplateArgument, 4> Converted;
2297 bool ExpansionIntoFixedList = false;
2298 if (SemaRef.CheckTemplateArgumentList(
2299 VarTemplate, VarTemplate->getLocStart(),
2300 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2301 Converted, &ExpansionIntoFixedList))
2302 return 0;
2303
2304 // Find the variable template specialization declaration that
2305 // corresponds to these arguments.
2306 void *InsertPos = 0;
2307 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2308 Converted.data(), Converted.size(), InsertPos))
2309 // If we already have a variable template specialization, return it.
2310 return VarSpec;
2311
2312 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2313 VarTemplateArgsInfo, Converted);
2314}
2315
2316Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2317 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2318 const TemplateArgumentListInfo &TemplateArgsInfo,
2319 SmallVectorImpl<TemplateArgument> &Converted) {
2320
2321 // If this is the variable for an anonymous struct or union,
2322 // instantiate the anonymous struct/union type first.
2323 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2324 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2325 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2326 return 0;
2327
2328 // Do substitution on the type of the declaration
2329 TypeSourceInfo *DI =
2330 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2331 D->getTypeSpecStartLoc(), D->getDeclName());
2332 if (!DI)
2333 return 0;
2334
2335 if (DI->getType()->isFunctionType()) {
2336 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2337 << D->isStaticDataMember() << DI->getType();
2338 return 0;
2339 }
2340
2341 // Build the instantiated declaration
2342 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2343 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2344 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2345 Converted.size());
2346 Var->setTemplateArgsInfo(TemplateArgsInfo);
2347 VarTemplate->AddSpecialization(Var, InsertPos);
2348
2349 // Substitute the nested name specifier, if any.
2350 if (SubstQualifier(D, Var))
2351 return 0;
2352
2353 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2354 StartingScope);
2355
2356 return Var;
2357}
2358
Eli Friedmanded99792013-06-27 23:21:55 +00002359Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2360 llvm_unreachable("@defs is not supported in Objective-C++");
2361}
2362
2363Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2364 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2365 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2366 DiagnosticsEngine::Error,
2367 "cannot instantiate %0 yet");
2368 SemaRef.Diag(D->getLocation(), DiagID)
2369 << D->getDeclKindName();
2370
2371 return 0;
2372}
2373
2374Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2375 llvm_unreachable("Unexpected decl");
2376}
2377
John McCallce3ff2b2009-08-25 22:02:44 +00002378Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002379 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002380 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002381 if (D->isInvalidDecl())
2382 return 0;
2383
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002384 return Instantiator.Visit(D);
2385}
2386
John McCalle29ba202009-08-20 01:44:21 +00002387/// \brief Instantiates a nested template parameter list in the current
2388/// instantiation context.
2389///
2390/// \param L The parameter list to instantiate
2391///
2392/// \returns NULL if there was an error
2393TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002394TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002395 // Get errors for all the parameters before bailing out.
2396 bool Invalid = false;
2397
2398 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002399 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002400 ParamVector Params;
2401 Params.reserve(N);
2402 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2403 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002404 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002405 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002406 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002407 }
2408
2409 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002410 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002411 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002412
2413 TemplateParameterList *InstL
2414 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2415 L->getLAngleLoc(), &Params.front(), N,
2416 L->getRAngleLoc());
2417 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002418}
John McCalle29ba202009-08-20 01:44:21 +00002419
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002420/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002421/// specialization.
2422///
2423/// \param ClassTemplate the (instantiated) class template that is partially
2424// specialized by the instantiation of \p PartialSpec.
2425///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002426/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002427/// specialization that we are instantiating.
2428///
Douglas Gregord65587f2010-11-10 19:44:59 +00002429/// \returns The instantiated partial specialization, if successful; otherwise,
2430/// NULL to indicate an error.
2431ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002432TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2433 ClassTemplateDecl *ClassTemplate,
2434 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002435 // Create a local instantiation scope for this class template partial
2436 // specialization, which will contain the instantiations of the template
2437 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002438 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002439
Douglas Gregored9c0f92009-10-29 00:04:11 +00002440 // Substitute into the template parameters of the class template partial
2441 // specialization.
2442 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2443 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2444 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002445 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002446
Douglas Gregored9c0f92009-10-29 00:04:11 +00002447 // Substitute into the template arguments of the class template partial
2448 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002449 const ASTTemplateArgumentListInfo *TemplArgInfo
2450 = PartialSpec->getTemplateArgsAsWritten();
2451 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2452 TemplArgInfo->RAngleLoc);
2453 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2454 TemplArgInfo->NumTemplateArgs,
Douglas Gregore02e2622010-12-22 21:19:48 +00002455 InstTemplateArgs, TemplateArgs))
2456 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002457
Douglas Gregored9c0f92009-10-29 00:04:11 +00002458 // Check that the template argument list is well-formed for this
2459 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002460 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002461 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002462 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002463 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002464 false,
2465 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002466 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002467
2468 // Figure out where to insert this class template partial specialization
2469 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002470 void *InsertPos = 0;
2471 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002472 = ClassTemplate->findPartialSpecialization(Converted.data(),
2473 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002474
Douglas Gregored9c0f92009-10-29 00:04:11 +00002475 // Build the canonical type that describes the converted template
2476 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002477 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002478 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002479 Converted.data(),
2480 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002481
2482 // Build the fully-sugared type for this class template
2483 // specialization as the user wrote in the specialization
2484 // itself. This means that we'll pretty-print the type retrieved
2485 // from the specialization's declaration the way that the user
2486 // actually wrote the specialization, rather than formatting the
2487 // name based on the "canonical" representation used to store the
2488 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002489 TypeSourceInfo *WrittenTy
2490 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2491 TemplateName(ClassTemplate),
2492 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002493 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002494 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002495
Douglas Gregored9c0f92009-10-29 00:04:11 +00002496 if (PrevDecl) {
2497 // We've already seen a partial specialization with the same template
2498 // parameters and template arguments. This can happen, for example, when
2499 // substituting the outer template arguments ends up causing two
2500 // class template partial specializations of a member class template
2501 // to have identical forms, e.g.,
2502 //
2503 // template<typename T, typename U>
2504 // struct Outer {
2505 // template<typename X, typename Y> struct Inner;
2506 // template<typename Y> struct Inner<T, Y>;
2507 // template<typename Y> struct Inner<U, Y>;
2508 // };
2509 //
2510 // Outer<int, int> outer; // error: the partial specializations of Inner
2511 // // have the same signature.
2512 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002513 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002514 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2515 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002516 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002517 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002518
2519
Douglas Gregored9c0f92009-10-29 00:04:11 +00002520 // Create the class template partial specialization declaration.
2521 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002522 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002523 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002524 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002525 PartialSpec->getLocStart(),
2526 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002527 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002528 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002529 Converted.data(),
2530 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002531 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002532 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002533 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002534 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002535 // Substitute the nested name specifier, if any.
2536 if (SubstQualifier(PartialSpec, InstPartialSpec))
2537 return 0;
2538
Douglas Gregored9c0f92009-10-29 00:04:11 +00002539 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002540 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002541
Douglas Gregored9c0f92009-10-29 00:04:11 +00002542 // Add this partial specialization to the set of class template partial
2543 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002544 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002545 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002546}
2547
Larisse Voufoef4579c2013-08-06 01:03:05 +00002548/// \brief Instantiate the declaration of a variable template partial
2549/// specialization.
2550///
2551/// \param VarTemplate the (instantiated) variable template that is partially
2552/// specialized by the instantiation of \p PartialSpec.
2553///
2554/// \param PartialSpec the (uninstantiated) variable template partial
2555/// specialization that we are instantiating.
2556///
2557/// \returns The instantiated partial specialization, if successful; otherwise,
2558/// NULL to indicate an error.
2559VarTemplatePartialSpecializationDecl *
2560TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2561 VarTemplateDecl *VarTemplate,
2562 VarTemplatePartialSpecializationDecl *PartialSpec) {
2563 // Create a local instantiation scope for this variable template partial
2564 // specialization, which will contain the instantiations of the template
2565 // parameters.
2566 LocalInstantiationScope Scope(SemaRef);
2567
2568 // Substitute into the template parameters of the variable template partial
2569 // specialization.
2570 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2571 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2572 if (!InstParams)
2573 return 0;
2574
2575 // Substitute into the template arguments of the variable template partial
2576 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002577 const ASTTemplateArgumentListInfo *TemplArgInfo
2578 = PartialSpec->getTemplateArgsAsWritten();
2579 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2580 TemplArgInfo->RAngleLoc);
2581 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2582 TemplArgInfo->NumTemplateArgs,
Larisse Voufoef4579c2013-08-06 01:03:05 +00002583 InstTemplateArgs, TemplateArgs))
2584 return 0;
2585
2586 // Check that the template argument list is well-formed for this
2587 // class template.
2588 SmallVector<TemplateArgument, 4> Converted;
2589 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2590 InstTemplateArgs, false, Converted))
2591 return 0;
2592
2593 // Figure out where to insert this variable template partial specialization
2594 // in the member template's set of variable template partial specializations.
2595 void *InsertPos = 0;
2596 VarTemplateSpecializationDecl *PrevDecl =
2597 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2598 InsertPos);
2599
2600 // Build the canonical type that describes the converted template
2601 // arguments of the variable template partial specialization.
2602 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2603 TemplateName(VarTemplate), Converted.data(), Converted.size());
2604
2605 // Build the fully-sugared type for this variable template
2606 // specialization as the user wrote in the specialization
2607 // itself. This means that we'll pretty-print the type retrieved
2608 // from the specialization's declaration the way that the user
2609 // actually wrote the specialization, rather than formatting the
2610 // name based on the "canonical" representation used to store the
2611 // template arguments in the specialization.
2612 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2613 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2614 CanonType);
2615
2616 if (PrevDecl) {
2617 // We've already seen a partial specialization with the same template
2618 // parameters and template arguments. This can happen, for example, when
2619 // substituting the outer template arguments ends up causing two
2620 // variable template partial specializations of a member variable template
2621 // to have identical forms, e.g.,
2622 //
2623 // template<typename T, typename U>
2624 // struct Outer {
2625 // template<typename X, typename Y> pair<X,Y> p;
2626 // template<typename Y> pair<T, Y> p;
2627 // template<typename Y> pair<U, Y> p;
2628 // };
2629 //
2630 // Outer<int, int> outer; // error: the partial specializations of Inner
2631 // // have the same signature.
2632 SemaRef.Diag(PartialSpec->getLocation(),
2633 diag::err_var_partial_spec_redeclared)
2634 << WrittenTy->getType();
2635 SemaRef.Diag(PrevDecl->getLocation(),
2636 diag::note_var_prev_partial_spec_here);
2637 return 0;
2638 }
2639
2640 // Do substitution on the type of the declaration
2641 TypeSourceInfo *DI = SemaRef.SubstType(
2642 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2643 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2644 if (!DI)
2645 return 0;
2646
2647 if (DI->getType()->isFunctionType()) {
2648 SemaRef.Diag(PartialSpec->getLocation(),
2649 diag::err_variable_instantiates_to_function)
2650 << PartialSpec->isStaticDataMember() << DI->getType();
2651 return 0;
2652 }
2653
2654 // Create the variable template partial specialization declaration.
2655 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2656 VarTemplatePartialSpecializationDecl::Create(
2657 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2658 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2659 DI, PartialSpec->getStorageClass(), Converted.data(),
2660 Converted.size(), InstTemplateArgs,
2661 VarTemplate->getNextPartialSpecSequenceNumber());
2662
2663 // Substitute the nested name specifier, if any.
2664 if (SubstQualifier(PartialSpec, InstPartialSpec))
2665 return 0;
2666
2667 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2668 InstPartialSpec->setTypeAsWritten(WrittenTy);
2669
2670 InstPartialSpec->setAccess(PartialSpec->getAccess());
2671 // FIXME: How much of BuildVariableInstantiation() should go in here?
2672
2673 // Add this partial specialization to the set of variable template partial
2674 // specializations. The instantiation of the initializer is not necessary.
2675 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2676 return InstPartialSpec;
2677}
2678
John McCall21ef0fa2010-03-11 09:03:00 +00002679TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002680TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002682 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2683 assert(OldTInfo && "substituting function without type source info");
2684 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002685
2686 CXXRecordDecl *ThisContext = 0;
2687 unsigned ThisTypeQuals = 0;
2688 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithcafeb942013-06-07 02:33:37 +00002689 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002690 ThisTypeQuals = Method->getTypeQualifiers();
2691 }
2692
John McCall6cd3b9f2010-04-09 17:38:44 +00002693 TypeSourceInfo *NewTInfo
2694 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2695 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002696 D->getDeclName(),
2697 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002698 if (!NewTInfo)
2699 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002700
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002701 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2702 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2703 if (NewTInfo != OldTInfo) {
2704 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002705 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002706 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002707 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002708 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002709 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002710 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002711 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2712
David Blaikiedc84cd52013-02-20 22:23:23 +00002713 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002714 if (OldParam->isParameterPack())
2715 NumArgumentsInExpansion =
2716 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2717 TemplateArgs);
2718 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002719 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002720 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002721 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002722 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002723 Scope->InstantiatedLocal(OldParam, NewParam);
2724 } else {
2725 // Parameter pack expansion: make the instantiation an argument pack.
2726 Scope->MakeInstantiatedLocalArgPack(OldParam);
2727 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002728 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002729 Params.push_back(NewParam);
2730 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2731 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002732 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002733 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002734 } else {
2735 // The function type itself was not dependent and therefore no
2736 // substitution occurred. However, we still need to instantiate
2737 // the function parameters themselves.
2738 const FunctionProtoType *OldProto =
2739 cast<FunctionProtoType>(OldProtoLoc.getType());
David Blaikie39e6ab42013-02-18 22:06:02 +00002740 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002741 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2742 if (!OldParam) {
2743 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2744 D, D->getLocation(), OldProto->getArgType(i)));
2745 continue;
2746 }
2747
Eli Friedmanded99792013-06-27 23:21:55 +00002748 ParmVarDecl *Parm =
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002749 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002750 if (!Parm)
2751 return 0;
2752 Params.push_back(Parm);
2753 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002754 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002755 } else {
2756 // If the type of this function, after ignoring parentheses, is not
2757 // *directly* a function type, then we're instantiating a function that
2758 // was declared via a typedef or with attributes, e.g.,
2759 //
2760 // typedef int functype(int, int);
2761 // functype func;
2762 // int __cdecl meth(int, int);
2763 //
2764 // In this case, we'll just go instantiate the ParmVarDecls that we
2765 // synthesized in the method declaration.
2766 SmallVector<QualType, 4> ParamTypes;
2767 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2768 D->getNumParams(), TemplateArgs, ParamTypes,
2769 &Params))
2770 return 0;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002771 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002772
John McCall21ef0fa2010-03-11 09:03:00 +00002773 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002774}
2775
Richard Smithe6975e92012-04-17 00:58:00 +00002776/// Introduce the instantiated function parameters into the local
2777/// instantiation scope, and set the parameter names to those used
2778/// in the template.
2779static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2780 const FunctionDecl *PatternDecl,
2781 LocalInstantiationScope &Scope,
2782 const MultiLevelTemplateArgumentList &TemplateArgs) {
2783 unsigned FParamIdx = 0;
2784 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2785 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2786 if (!PatternParam->isParameterPack()) {
2787 // Simple case: not a parameter pack.
2788 assert(FParamIdx < Function->getNumParams());
2789 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2790 FunctionParam->setDeclName(PatternParam->getDeclName());
2791 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2792 ++FParamIdx;
2793 continue;
2794 }
2795
2796 // Expand the parameter pack.
2797 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002798 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002799 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002800 assert(NumArgumentsInExpansion &&
2801 "should only be called when all template arguments are known");
2802 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002803 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2804 FunctionParam->setDeclName(PatternParam->getDeclName());
2805 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2806 ++FParamIdx;
2807 }
2808 }
2809}
2810
2811static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2812 const FunctionProtoType *Proto,
2813 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002814 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2815
Richard Smithe6975e92012-04-17 00:58:00 +00002816 // C++11 [expr.prim.general]p3:
2817 // If a declaration declares a member function or member function
2818 // template of a class X, the expression this is a prvalue of type
2819 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2820 // and the end of the function-definition, member-declarator, or
2821 // declarator.
2822 CXXRecordDecl *ThisContext = 0;
2823 unsigned ThisTypeQuals = 0;
2824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2825 ThisContext = Method->getParent();
2826 ThisTypeQuals = Method->getTypeQualifiers();
2827 }
2828 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002829 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002830
2831 // The function has an exception specification or a "noreturn"
2832 // attribute. Substitute into each of the exception types.
2833 SmallVector<QualType, 4> Exceptions;
2834 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2835 // FIXME: Poor location information!
2836 if (const PackExpansionType *PackExpansion
2837 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2838 // We have a pack expansion. Instantiate it.
2839 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2840 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2841 Unexpanded);
2842 assert(!Unexpanded.empty() &&
2843 "Pack expansion without parameter packs?");
2844
2845 bool Expand = false;
2846 bool RetainExpansion = false;
Richard Smithcafeb942013-06-07 02:33:37 +00002847 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithe6975e92012-04-17 00:58:00 +00002848 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2849 SourceRange(),
2850 Unexpanded,
2851 TemplateArgs,
2852 Expand,
2853 RetainExpansion,
2854 NumExpansions))
2855 break;
2856
2857 if (!Expand) {
2858 // We can't expand this pack expansion into separate arguments yet;
2859 // just substitute into the pattern and create a new pack expansion
2860 // type.
2861 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2862 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2863 TemplateArgs,
2864 New->getLocation(), New->getDeclName());
2865 if (T.isNull())
2866 break;
2867
2868 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2869 Exceptions.push_back(T);
2870 continue;
2871 }
2872
2873 // Substitute into the pack expansion pattern for each template
2874 bool Invalid = false;
2875 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2876 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2877
2878 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2879 TemplateArgs,
2880 New->getLocation(), New->getDeclName());
2881 if (T.isNull()) {
2882 Invalid = true;
2883 break;
2884 }
2885
2886 Exceptions.push_back(T);
2887 }
2888
2889 if (Invalid)
2890 break;
2891
2892 continue;
2893 }
2894
2895 QualType T
2896 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2897 New->getLocation(), New->getDeclName());
2898 if (T.isNull() ||
2899 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2900 continue;
2901
2902 Exceptions.push_back(T);
2903 }
2904 Expr *NoexceptExpr = 0;
2905 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2906 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2907 Sema::ConstantEvaluated);
2908 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2909 if (E.isUsable())
2910 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2911
2912 if (E.isUsable()) {
2913 NoexceptExpr = E.take();
2914 if (!NoexceptExpr->isTypeDependent() &&
2915 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002916 NoexceptExpr
2917 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2918 0, diag::err_noexcept_needs_constant_expression,
2919 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002920 }
2921 }
2922
2923 // Rebuild the function type
2924 const FunctionProtoType *NewProto
2925 = New->getType()->getAs<FunctionProtoType>();
2926 assert(NewProto && "Template instantiation without function prototype?");
2927
2928 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2929 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2930 EPI.NumExceptions = Exceptions.size();
2931 EPI.Exceptions = Exceptions.data();
2932 EPI.NoexceptExpr = NoexceptExpr;
2933
2934 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002935 NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002936}
2937
2938void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2939 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002940 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2941 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002942 return;
2943
2944 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2945 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002946 if (Inst) {
2947 // We hit the instantiation depth limit. Clear the exception specification
2948 // so that our callers don't have to cope with EST_Uninstantiated.
2949 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2950 EPI.ExceptionSpecType = EST_None;
2951 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002952 Proto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002953 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002954 }
Richard Smithe6975e92012-04-17 00:58:00 +00002955
2956 // Enter the scope of this instantiation. We don't use
2957 // PushDeclContext because we don't have a scope.
2958 Sema::ContextRAII savedContext(*this, Decl);
2959 LocalInstantiationScope Scope(*this);
2960
2961 MultiLevelTemplateArgumentList TemplateArgs =
2962 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2963
Richard Smith13bffc52012-04-19 00:08:28 +00002964 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2965 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002966
Richard Smith13bffc52012-04-19 00:08:28 +00002967 ::InstantiateExceptionSpec(*this, Decl,
2968 Template->getType()->castAs<FunctionProtoType>(),
2969 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002970}
2971
Mike Stump1eb44332009-09-09 15:08:12 +00002972/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002973/// declaration (New) from the corresponding fields of its template (Tmpl).
2974///
2975/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002976bool
2977TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002978 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002979 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002980 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002981
Douglas Gregorcca9e962009-07-01 22:01:06 +00002982 // If we are performing substituting explicitly-specified template arguments
2983 // or deduced template arguments into a function template and we reach this
2984 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002985 // to keeping the new function template specialization. We therefore
2986 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002987 // into a template instantiation for this specific function template
2988 // specialization, which is not a SFINAE context, so that we diagnose any
2989 // further errors in the declaration itself.
2990 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2991 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2992 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2993 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002994 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002995 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002996 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002997 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002998 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002999 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00003000 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00003001 }
3002 }
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00003004 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3005 assert(Proto && "Function template without prototype?");
3006
Sebastian Redl60618fa2011-03-12 11:50:43 +00003007 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00003008 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00003009
Richard Smithe6975e92012-04-17 00:58:00 +00003010 // DR1330: In C++11, defer instantiation of a non-trivial
3011 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00003012 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00003013 EPI.ExceptionSpecType != EST_None &&
3014 EPI.ExceptionSpecType != EST_DynamicNone &&
3015 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00003016 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3017 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3018 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith4841ca52013-04-10 05:48:59 +00003019 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3020 if (EPI.ExceptionSpecType == EST_Unevaluated)
3021 NewEST = EST_Unevaluated;
Richard Smith13bffc52012-04-19 00:08:28 +00003022
Richard Smithe6975e92012-04-17 00:58:00 +00003023 // Mark the function has having an uninstantiated exception specification.
3024 const FunctionProtoType *NewProto
3025 = New->getType()->getAs<FunctionProtoType>();
3026 assert(NewProto && "Template instantiation without function prototype?");
3027 EPI = NewProto->getExtProtoInfo();
Richard Smith4841ca52013-04-10 05:48:59 +00003028 EPI.ExceptionSpecType = NewEST;
Richard Smithe6975e92012-04-17 00:58:00 +00003029 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00003030 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner0567a792013-06-10 20:51:09 +00003031 New->setType(SemaRef.Context.getFunctionType(
3032 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00003033 } else {
3034 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3035 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00003036 }
3037
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003038 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00003039 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003040 Tmpl->isDefined(Definition);
3041
DeLesley Hutchins23323e02012-01-20 22:50:54 +00003042 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3043 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00003044
Douglas Gregore53060f2009-06-25 22:08:12 +00003045 return false;
3046}
3047
Douglas Gregor5545e162009-03-24 00:38:23 +00003048/// \brief Initializes common fields of an instantiated method
3049/// declaration (New) from the corresponding fields of its template
3050/// (Tmpl).
3051///
3052/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00003053bool
3054TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00003055 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003056 if (InitFunctionInstantiation(New, Tmpl))
3057 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Douglas Gregor5545e162009-03-24 00:38:23 +00003059 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00003060 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00003061 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00003062
Douglas Gregor5545e162009-03-24 00:38:23 +00003063 // FIXME: New needs a pointer to Tmpl
3064 return false;
3065}
Douglas Gregora58861f2009-05-13 20:28:22 +00003066
3067/// \brief Instantiate the definition of the given function from its
3068/// template.
3069///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003070/// \param PointOfInstantiation the point at which the instantiation was
3071/// required. Note that this is not precisely a "point of instantiation"
3072/// for the function, but it's close.
3073///
Douglas Gregora58861f2009-05-13 20:28:22 +00003074/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003075/// function template specialization or member function of a class template
3076/// specialization.
3077///
3078/// \param Recursive if true, recursively instantiates any functions that
3079/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003080///
3081/// \param DefinitionRequired if true, then we are performing an explicit
3082/// instantiation where the body of the function is required. Complain if
3083/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003084void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003085 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003086 bool Recursive,
3087 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00003088 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003089 return;
3090
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003091 // Never instantiate an explicit specialization except if it is a class scope
3092 // explicit specialization.
3093 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3094 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003095 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00003096
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003097 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00003098 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00003099 assert(PatternDecl && "instantiating a non-template");
3100
3101 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3102 assert(PatternDecl && "template definition is not a template");
3103 if (!Pattern) {
3104 // Try to find a defaulted definition
3105 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00003106 }
Sean Huntf996e052011-05-27 20:00:14 +00003107 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003108
Francois Pichet8387e2a2011-04-22 22:18:13 +00003109 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00003110 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00003111 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00003112 PendingInstantiations.push_back(
3113 std::make_pair(Function, PointOfInstantiation));
3114 return;
3115 }
3116
3117 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003118 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00003119 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00003120 LateTemplateParser) {
Richard Smithac32d902013-08-07 21:41:30 +00003121 // FIXME: Optimize to allow individual templates to be deserialized.
3122 if (PatternDecl->isFromASTFile())
3123 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3124
3125 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3126 assert(LPT && "missing LateParsedTemplate");
3127 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet8387e2a2011-04-22 22:18:13 +00003128 Pattern = PatternDecl->getBody(PatternDecl);
3129 }
3130
Sean Huntf996e052011-05-27 20:00:14 +00003131 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003132 if (DefinitionRequired) {
3133 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003134 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003135 diag::err_explicit_instantiation_undefined_func_template)
3136 << Function->getPrimaryTemplate();
3137 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003138 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003139 diag::err_explicit_instantiation_undefined_member)
3140 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003141
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003142 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003143 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003144 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00003145 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003146 } else if (Function->getTemplateSpecializationKind()
3147 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003148 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003149 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003150 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00003151
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003152 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003153 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003154
Richard Smith60e141e2013-05-04 07:00:32 +00003155 // C++1y [temp.explicit]p10:
3156 // Except for inline functions, declarations with types deduced from their
3157 // initializer or return value, and class template specializations, other
3158 // explicit instantiation declarations have the effect of suppressing the
3159 // implicit instantiation of the entity to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00003160 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003161 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith60e141e2013-05-04 07:00:32 +00003162 !PatternDecl->isInlined() &&
3163 !PatternDecl->getResultType()->isUndeducedType())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003164 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003165
Richard Smithd4497dd2013-01-25 00:08:28 +00003166 if (PatternDecl->isInlined())
3167 Function->setImplicitlyInline();
3168
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003169 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3170 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003171 return;
3172
Abramo Bagnarae9946242011-11-18 08:08:52 +00003173 // Copy the inner loc start from the pattern.
3174 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3175
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003176 // If we're performing recursive template instantiation, create our own
3177 // queue of pending implicit instantiations that we will instantiate later,
3178 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003179 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003180 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Faisal Vali86648b12013-06-26 02:34:24 +00003181 std::deque<PendingImplicitInstantiation>
3182 SavedPendingLocalImplicitInstantiations;
3183 SavedPendingLocalImplicitInstantiations.swap(
3184 PendingLocalImplicitInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003185 if (Recursive) {
3186 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003187 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003188 }
Mike Stump1eb44332009-09-09 15:08:12 +00003189
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003190 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00003191 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003192
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003193 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00003194 // recorded, unless we're actually a member function within a local
3195 // class, in which case we need to merge our results with the parent
3196 // scope (of the enclosing function).
3197 bool MergeWithParentScope = false;
3198 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3199 MergeWithParentScope = Rec->isLocalClass();
3200
3201 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Richard Smith1d28caf2012-12-11 01:14:52 +00003203 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00003204 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00003205 else {
3206 ActOnStartOfFunctionDef(0, Function);
3207
3208 // Enter the scope of this instantiation. We don't use
3209 // PushDeclContext because we don't have a scope.
3210 Sema::ContextRAII savedContext(*this, Function);
3211
3212 MultiLevelTemplateArgumentList TemplateArgs =
3213 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3214
3215 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3216 TemplateArgs);
3217
Sean Huntcd10dec2011-05-23 23:14:04 +00003218 // If this is a constructor, instantiate the member initializers.
3219 if (const CXXConstructorDecl *Ctor =
3220 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3221 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3222 TemplateArgs);
3223 }
3224
3225 // Instantiate the function body.
3226 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3227
3228 if (Body.isInvalid())
3229 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003230
Sean Huntcd10dec2011-05-23 23:14:04 +00003231 ActOnFinishFunctionBody(Function, Body.get(),
3232 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00003233
3234 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3235
3236 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00003237 }
3238
Douglas Gregoraba43bb2009-05-26 20:50:29 +00003239 DeclGroupRef DG(Function);
3240 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Douglas Gregor60406be2010-01-16 22:29:39 +00003242 // This class may have local implicit instantiations that need to be
3243 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003244 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00003245 Scope.Exit();
3246
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003247 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003248 // Define any pending vtables.
3249 DefineUsedVTables();
3250
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003251 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003252 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003253 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003254
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003255 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00003256 assert(VTableUses.empty() &&
3257 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003258 VTableUses.swap(SavedVTableUses);
3259
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003260 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003261 assert(PendingInstantiations.empty() &&
3262 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003263 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003264 }
Faisal Vali86648b12013-06-26 02:34:24 +00003265 SavedPendingLocalImplicitInstantiations.swap(
3266 PendingLocalImplicitInstantiations);
Douglas Gregora58861f2009-05-13 20:28:22 +00003267}
3268
Larisse Voufoef4579c2013-08-06 01:03:05 +00003269VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3270 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3271 const TemplateArgumentList &TemplateArgList,
3272 const TemplateArgumentListInfo &TemplateArgsInfo,
3273 SmallVectorImpl<TemplateArgument> &Converted,
3274 SourceLocation PointOfInstantiation, void *InsertPos,
3275 LateInstantiatedAttrVec *LateAttrs,
3276 LocalInstantiationScope *StartingScope) {
3277 if (FromVar->isInvalidDecl())
3278 return 0;
3279
3280 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3281 if (Inst)
3282 return 0;
3283
3284 MultiLevelTemplateArgumentList TemplateArgLists;
3285 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3286
3287 TemplateDeclInstantiator Instantiator(
3288 *this, VarTemplate->getDeclContext(),
3289 MultiLevelTemplateArgumentList(TemplateArgList));
3290
3291 // TODO: Set LateAttrs and StartingScope ...
3292
3293 return cast_or_null<VarTemplateSpecializationDecl>(
3294 Instantiator.VisitVarTemplateSpecializationDecl(
3295 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3296}
3297
3298/// \brief Instantiates a variable template specialization by completing it
3299/// with appropriate type information and initializer.
3300VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3301 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3302 const MultiLevelTemplateArgumentList &TemplateArgs) {
3303
3304 // Do substitution on the type of the declaration
3305 TypeSourceInfo *DI =
3306 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3307 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3308 if (!DI)
3309 return 0;
3310
3311 // Update the type of this variable template specialization.
3312 VarSpec->setType(DI->getType());
3313
3314 // Instantiate the initializer.
3315 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3316
3317 return VarSpec;
3318}
3319
3320/// BuildVariableInstantiation - Used after a new variable has been created.
3321/// Sets basic variable data and decides whether to postpone the
3322/// variable instantiation.
3323void Sema::BuildVariableInstantiation(
3324 VarDecl *NewVar, VarDecl *OldVar,
3325 const MultiLevelTemplateArgumentList &TemplateArgs,
3326 LateInstantiatedAttrVec *LateAttrs,
3327 LocalInstantiationScope *StartingScope,
3328 bool ForVarTemplate) {
3329
3330 // If we are instantiating a static data member defined
3331 // out-of-line, the instantiation will have the same lexical
3332 // context (which will be a namespace scope) as the template.
3333 if (OldVar->isOutOfLine())
3334 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3335 NewVar->setTSCSpec(OldVar->getTSCSpec());
3336 NewVar->setInitStyle(OldVar->getInitStyle());
3337 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3338 NewVar->setConstexpr(OldVar->isConstexpr());
3339 NewVar->setAccess(OldVar->getAccess());
3340
3341 if (!OldVar->isStaticDataMember()) {
3342 NewVar->setUsed(OldVar->isUsed(false));
3343 NewVar->setReferenced(OldVar->isReferenced());
3344 }
3345
3346 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3347
3348 if (NewVar->hasAttrs())
3349 CheckAlignasUnderalignment(NewVar);
3350
3351 // FIXME: In theory, we could have a previous declaration for variables that
3352 // are not static data members.
3353 // FIXME: having to fake up a LookupResult is dumb.
3354 LookupResult Previous(*this, NewVar->getDeclName(), NewVar->getLocation(),
3355 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3356
3357 if (!isa<VarTemplateSpecializationDecl>(NewVar))
3358 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3359
3360 CheckVariableDeclaration(NewVar, Previous);
3361
3362 if (OldVar->isOutOfLine()) {
3363 OldVar->getLexicalDeclContext()->addDecl(NewVar);
3364 if (!ForVarTemplate)
3365 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3366 } else {
3367 if (!ForVarTemplate)
3368 NewVar->getDeclContext()->addDecl(NewVar);
3369 if (NewVar->getDeclContext()->isFunctionOrMethod())
3370 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3371 }
3372
3373 // Link instantiations of static data members back to the template from
3374 // which they were instantiated.
3375 if (NewVar->isStaticDataMember() && !ForVarTemplate)
3376 NewVar->setInstantiationOfStaticDataMember(OldVar,
3377 TSK_ImplicitInstantiation);
3378
3379 if (isa<VarTemplateSpecializationDecl>(NewVar)) {
3380 // Do not instantiate the variable just yet.
3381 } else
3382 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3383
3384 // Diagnose unused local variables with dependent types, where the diagnostic
3385 // will have been deferred.
3386 if (!NewVar->isInvalidDecl() &&
3387 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3388 OldVar->getType()->isDependentType())
3389 DiagnoseUnusedDecl(NewVar);
3390}
3391
3392/// \brief Instantiate the initializer of a variable.
3393void Sema::InstantiateVariableInitializer(
3394 VarDecl *Var, VarDecl *OldVar,
3395 const MultiLevelTemplateArgumentList &TemplateArgs) {
3396
3397 if (Var->getAnyInitializer())
3398 // We already have an initializer in the class.
3399 return;
3400
3401 if (OldVar->getInit()) {
3402 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3403 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3404 else
3405 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3406
3407 // Instantiate the initializer.
3408 ExprResult Init =
3409 SubstInitializer(OldVar->getInit(), TemplateArgs,
3410 OldVar->getInitStyle() == VarDecl::CallInit);
3411 if (!Init.isInvalid()) {
3412 bool TypeMayContainAuto = true;
3413 if (Init.get()) {
3414 bool DirectInit = OldVar->isDirectInit();
3415 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3416 } else
3417 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3418 } else {
3419 // FIXME: Not too happy about invalidating the declaration
3420 // because of a bogus initializer.
3421 Var->setInvalidDecl();
3422 }
3423
3424 PopExpressionEvaluationContext();
3425 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3426 !Var->isCXXForRangeDecl())
3427 ActOnUninitializedDecl(Var, false);
3428}
3429
Douglas Gregora58861f2009-05-13 20:28:22 +00003430/// \brief Instantiate the definition of the given variable from its
3431/// template.
3432///
Douglas Gregor7caa6822009-07-24 20:34:43 +00003433/// \param PointOfInstantiation the point at which the instantiation was
3434/// required. Note that this is not precisely a "point of instantiation"
3435/// for the function, but it's close.
3436///
3437/// \param Var the already-instantiated declaration of a static member
3438/// variable of a class template specialization.
3439///
3440/// \param Recursive if true, recursively instantiates any functions that
3441/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003442///
3443/// \param DefinitionRequired if true, then we are performing an explicit
3444/// instantiation where an out-of-line definition of the member variable
3445/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00003446void Sema::InstantiateStaticDataMemberDefinition(
3447 SourceLocation PointOfInstantiation,
3448 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003449 bool Recursive,
3450 bool DefinitionRequired) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003451 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3452 DefinitionRequired);
3453}
3454
3455void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3456 VarDecl *Var, bool Recursive,
3457 bool DefinitionRequired) {
3458
Douglas Gregor7caa6822009-07-24 20:34:43 +00003459 if (Var->isInvalidDecl())
3460 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Larisse Voufoef4579c2013-08-06 01:03:05 +00003462 VarTemplateSpecializationDecl *VarSpec =
3463 dyn_cast<VarTemplateSpecializationDecl>(Var);
3464 assert((VarSpec || Var->isStaticDataMember()) &&
3465 "Not a static data member, nor a variable template specialization?");
3466 VarDecl *PatternDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Larisse Voufoef4579c2013-08-06 01:03:05 +00003468 // If this is a variable template specialization, make sure that it is
3469 // non-dependent, then find its instantiation pattern.
3470 if (VarSpec) {
3471 bool InstantiationDependent = false;
3472 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3473 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3474 "Only instantiate variable template specializations that are "
3475 "not type-dependent");
Larisse Voufo3151b7c2013-08-06 03:57:41 +00003476 (void)InstantiationDependent;
Larisse Voufoef4579c2013-08-06 01:03:05 +00003477
3478 // Find the variable initialization that we'll be substituting.
3479 assert(VarSpec->getSpecializedTemplate() &&
3480 "Specialization without specialized template?");
3481 llvm::PointerUnion<VarTemplateDecl *,
3482 VarTemplatePartialSpecializationDecl *> PatternPtr =
3483 VarSpec->getSpecializedTemplateOrPartial();
3484 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>())
3485 PatternDecl = cast<VarDecl>(
3486 PatternPtr.get<VarTemplatePartialSpecializationDecl *>());
3487 else
3488 PatternDecl = (PatternPtr.get<VarTemplateDecl *>())->getTemplatedDecl();
3489 assert(PatternDecl && "instantiating a non-template");
3490 }
3491
3492 // If this is a static data member, find its out-of-line definition.
3493 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
3494 if (Var->isStaticDataMember()) {
3495 assert(Def && "This data member was not instantiated from a template?");
3496 assert(Def->isStaticDataMember() && "Not a static data member?");
3497 Def = Def->getOutOfLineDefinition();
3498 }
3499
3500 // If the instantiation pattern does not have an initializer, or if an
3501 // out-of-line definition is not found, we won't perform any instantiation.
3502 // Rather, we rely on the user to instantiate this definition (or provide
3503 // a specialization for it) in another translation unit.
3504 if ((VarSpec && !PatternDecl->getInit()) ||
3505 (!VarSpec && Var->isStaticDataMember() && !Def)) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003506 if (DefinitionRequired) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003507 if (!Var->isStaticDataMember()) {
3508 Diag(PointOfInstantiation,
3509 diag::err_explicit_instantiation_undefined_var_template)
3510 << PatternDecl;
3511 Diag(PatternDecl->getLocation(),
3512 diag::note_explicit_instantiation_here);
3513 } else {
3514 Def = Var->getInstantiatedFromStaticDataMember();
3515 Diag(PointOfInstantiation,
3516 diag::err_explicit_instantiation_undefined_member)
3517 << 3 << Var->getDeclName() << Var->getDeclContext();
3518 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
3519 }
3520 if (VarSpec)
3521 Var->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003522 } else if (Var->getTemplateSpecializationKind()
3523 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003524 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003525 std::make_pair(Var, PointOfInstantiation));
3526 }
3527
Douglas Gregor7caa6822009-07-24 20:34:43 +00003528 return;
3529 }
3530
Rafael Espindola234fe652012-03-05 10:54:55 +00003531 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3532
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003533 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00003534 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003535 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003536
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003537 // C++0x [temp.explicit]p9:
3538 // Except for inline functions, other explicit instantiation declarations
3539 // have the effect of suppressing the implicit instantiation of the entity
3540 // to which they refer.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003541 //
3542 // C++11 [temp.explicit]p10:
3543 // Except for inline functions, [...] explicit instantiation declarations
3544 // have the effect of suppressing the implicit instantiation of the entity
3545 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00003546 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003547 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003549 // Make sure to pass the instantiated variable to the consumer at the end.
3550 struct PassToConsumerRAII {
3551 ASTConsumer &Consumer;
3552 VarDecl *Var;
3553
3554 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3555 : Consumer(Consumer), Var(Var) { }
3556
3557 ~PassToConsumerRAII() {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003558 if (Var->isStaticDataMember())
3559 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3560 else {
3561 DeclGroupRef DG(Var);
3562 Consumer.HandleTopLevelDecl(DG);
3563 }
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003564 }
3565 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00003566
Larisse Voufoef4579c2013-08-06 01:03:05 +00003567 if (!VarSpec) {
3568 // If we already have a definition, we're done.
3569 if (VarDecl *Def = Var->getDefinition()) {
3570 // We may be explicitly instantiating something we've already implicitly
3571 // instantiated.
3572 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3573 PointOfInstantiation);
3574 return;
3575 }
Nick Lewycky95e38722012-04-04 02:38:36 +00003576 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003577
Douglas Gregor7caa6822009-07-24 20:34:43 +00003578 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3579 if (Inst)
3580 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Douglas Gregor7caa6822009-07-24 20:34:43 +00003582 // If we're performing recursive template instantiation, create our own
3583 // queue of pending implicit instantiations that we will instantiate later,
3584 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003585 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003586 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003587 if (Recursive) {
3588 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003589 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003590 }
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Douglas Gregor7caa6822009-07-24 20:34:43 +00003592 // Enter the scope of this instantiation. We don't use
3593 // PushDeclContext because we don't have a scope.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003594 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003595 LocalInstantiationScope Local(*this);
John McCallf5ba7e02011-02-14 20:37:25 +00003596
Larisse Voufoef4579c2013-08-06 01:03:05 +00003597 VarDecl *OldVar = Var;
3598 if (!VarSpec)
3599 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3600 getTemplateInstantiationArgs(Var)));
3601 else
3602 // Construct a VarTemplateSpecializationDecl to avoid name clashing with
3603 // the primary template. (Note that unlike function declarations, variable
3604 // declarations cannot be overloaded.)
3605 // In fact, there is no need to construct a new declaration from scratch.
3606 // Thus, simply complete its definition with an appropriately substituted
3607 // type and initializer.
3608 Var = CompleteVarTemplateSpecializationDecl(
3609 VarSpec, PatternDecl, getTemplateInstantiationArgs(Var));
3610
3611 PreviousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003612
3613 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00003614 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
Larisse Voufoef4579c2013-08-06 01:03:05 +00003615 if (!VarSpec)
3616 assert(MSInfo && "Missing member specialization information?");
3617
3618 PassToConsumerRAII.Var = Var;
3619 if (MSInfo)
3620 Var->setTemplateSpecializationKind(
3621 MSInfo->getTemplateSpecializationKind(),
3622 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003623 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00003624
3625 // This variable may have local implicit instantiations that need to be
3626 // instantiated within this scope.
3627 PerformPendingInstantiations(/*LocalOnly=*/true);
3628
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003629 Local.Exit();
3630
Douglas Gregor7caa6822009-07-24 20:34:43 +00003631 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003632 // Define any newly required vtables.
3633 DefineUsedVTables();
3634
Douglas Gregor7caa6822009-07-24 20:34:43 +00003635 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003636 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003637 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Nick Lewycky81559102011-05-31 07:58:42 +00003639 // Restore the set of pending vtables.
3640 assert(VTableUses.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003641 "VTableUses should be empty before it is discarded.");
Nick Lewycky81559102011-05-31 07:58:42 +00003642 VTableUses.swap(SavedVTableUses);
3643
Douglas Gregor7caa6822009-07-24 20:34:43 +00003644 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003645 assert(PendingInstantiations.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003646 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003647 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003648 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003649}
Douglas Gregor815215d2009-05-27 05:35:12 +00003650
Anders Carlsson09025312009-08-29 05:16:22 +00003651void
3652Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3653 const CXXConstructorDecl *Tmpl,
3654 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Richard Trieu90ab75b2011-09-09 03:18:59 +00003656 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003657 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003658
Anders Carlsson09025312009-08-29 05:16:22 +00003659 // Instantiate all the initializers.
3660 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003661 InitsEnd = Tmpl->init_end();
3662 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003663 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003664
Chandler Carruth030ef472010-09-03 21:54:20 +00003665 // Only instantiate written initializers, let Sema re-construct implicit
3666 // ones.
3667 if (!Init->isWritten())
3668 continue;
3669
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003670 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003671
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003672 if (Init->isPackExpansion()) {
3673 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003674 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky98a75582013-06-13 00:45:47 +00003675 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003676 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky98a75582013-06-13 00:45:47 +00003677 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003678 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003679 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003680 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003681 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003682 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003683 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003684 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003685 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003686 NumExpansions)) {
3687 AnyErrors = true;
3688 New->setInvalidDecl();
3689 continue;
3690 }
3691 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003692
3693 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003694 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003695 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3696
3697 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003698 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3699 /*CXXDirectInit=*/true);
3700 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003701 AnyErrors = true;
3702 break;
3703 }
3704
3705 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003706 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003707 TemplateArgs,
3708 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003709 New->getDeclName());
3710 if (!BaseTInfo) {
3711 AnyErrors = true;
3712 break;
3713 }
3714
3715 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003716 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003717 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003718 New->getParent(),
3719 SourceLocation());
3720 if (NewInit.isInvalid()) {
3721 AnyErrors = true;
3722 break;
3723 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003724
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003725 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003726 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003727
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003728 continue;
3729 }
3730
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003731 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003732 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3733 /*CXXDirectInit=*/true);
3734 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003735 AnyErrors = true;
3736 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003737 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003738
Anders Carlsson09025312009-08-29 05:16:22 +00003739 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003740 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3741 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3742 TemplateArgs,
3743 Init->getSourceLocation(),
3744 New->getDeclName());
3745 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003746 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003747 New->setInvalidDecl();
3748 continue;
3749 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003750
Douglas Gregor76852c22011-11-01 01:16:03 +00003751 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003752 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003753 New->getParent(), EllipsisLoc);
3754 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003755 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003756 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003757 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003758 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003759 Init->getMemberLocation(),
3760 Init->getMember(),
3761 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003762 if (!Member) {
3763 AnyErrors = true;
3764 New->setInvalidDecl();
3765 continue;
3766 }
Mike Stump1eb44332009-09-09 15:08:12 +00003767
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003768 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003769 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003770 } else if (Init->isIndirectMemberInitializer()) {
3771 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003772 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003773 Init->getMemberLocation(),
3774 Init->getIndirectMember(), TemplateArgs));
3775
Douglas Gregorb7107222011-03-04 19:46:35 +00003776 if (!IndirectMember) {
3777 AnyErrors = true;
3778 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003779 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003780 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003781
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003782 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003783 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003784 }
3785
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003786 if (NewInit.isInvalid()) {
3787 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003788 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003789 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003790 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003791 }
3792 }
Mike Stump1eb44332009-09-09 15:08:12 +00003793
Anders Carlsson09025312009-08-29 05:16:22 +00003794 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003795 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003796 /*FIXME: ColonLoc */
3797 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003798 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003799 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003800}
3801
John McCall52a575a2009-08-29 08:11:13 +00003802// TODO: this could be templated if the various decl types used the
3803// same method name.
3804static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3805 ClassTemplateDecl *Instance) {
3806 Pattern = Pattern->getCanonicalDecl();
3807
3808 do {
3809 Instance = Instance->getCanonicalDecl();
3810 if (Pattern == Instance) return true;
3811 Instance = Instance->getInstantiatedFromMemberTemplate();
3812 } while (Instance);
3813
3814 return false;
3815}
3816
Douglas Gregor0d696532009-09-28 06:34:35 +00003817static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3818 FunctionTemplateDecl *Instance) {
3819 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003820
Douglas Gregor0d696532009-09-28 06:34:35 +00003821 do {
3822 Instance = Instance->getCanonicalDecl();
3823 if (Pattern == Instance) return true;
3824 Instance = Instance->getInstantiatedFromMemberTemplate();
3825 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003826
Douglas Gregor0d696532009-09-28 06:34:35 +00003827 return false;
3828}
3829
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003830static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003831isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3832 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003833 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003834 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3835 do {
3836 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3837 Instance->getCanonicalDecl());
3838 if (Pattern == Instance)
3839 return true;
3840 Instance = Instance->getInstantiatedFromMember();
3841 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003842
Douglas Gregored9c0f92009-10-29 00:04:11 +00003843 return false;
3844}
3845
John McCall52a575a2009-08-29 08:11:13 +00003846static bool isInstantiationOf(CXXRecordDecl *Pattern,
3847 CXXRecordDecl *Instance) {
3848 Pattern = Pattern->getCanonicalDecl();
3849
3850 do {
3851 Instance = Instance->getCanonicalDecl();
3852 if (Pattern == Instance) return true;
3853 Instance = Instance->getInstantiatedFromMemberClass();
3854 } while (Instance);
3855
3856 return false;
3857}
3858
3859static bool isInstantiationOf(FunctionDecl *Pattern,
3860 FunctionDecl *Instance) {
3861 Pattern = Pattern->getCanonicalDecl();
3862
3863 do {
3864 Instance = Instance->getCanonicalDecl();
3865 if (Pattern == Instance) return true;
3866 Instance = Instance->getInstantiatedFromMemberFunction();
3867 } while (Instance);
3868
3869 return false;
3870}
3871
3872static bool isInstantiationOf(EnumDecl *Pattern,
3873 EnumDecl *Instance) {
3874 Pattern = Pattern->getCanonicalDecl();
3875
3876 do {
3877 Instance = Instance->getCanonicalDecl();
3878 if (Pattern == Instance) return true;
3879 Instance = Instance->getInstantiatedFromMemberEnum();
3880 } while (Instance);
3881
3882 return false;
3883}
3884
John McCalled976492009-12-04 22:46:56 +00003885static bool isInstantiationOf(UsingShadowDecl *Pattern,
3886 UsingShadowDecl *Instance,
3887 ASTContext &C) {
3888 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3889}
3890
3891static bool isInstantiationOf(UsingDecl *Pattern,
3892 UsingDecl *Instance,
3893 ASTContext &C) {
3894 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3895}
3896
John McCall7ba107a2009-11-18 02:36:19 +00003897static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3898 UsingDecl *Instance,
3899 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003900 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003901}
3902
3903static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003904 UsingDecl *Instance,
3905 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003906 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003907}
3908
John McCall52a575a2009-08-29 08:11:13 +00003909static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3910 VarDecl *Instance) {
3911 assert(Instance->isStaticDataMember());
3912
3913 Pattern = Pattern->getCanonicalDecl();
3914
3915 do {
3916 Instance = Instance->getCanonicalDecl();
3917 if (Pattern == Instance) return true;
3918 Instance = Instance->getInstantiatedFromStaticDataMember();
3919 } while (Instance);
3920
3921 return false;
3922}
3923
John McCalled976492009-12-04 22:46:56 +00003924// Other is the prospective instantiation
3925// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003926static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003927 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003928 if (UnresolvedUsingTypenameDecl *UUD
3929 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3930 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3931 return isInstantiationOf(UUD, UD, Ctx);
3932 }
3933 }
3934
3935 if (UnresolvedUsingValueDecl *UUD
3936 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003937 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3938 return isInstantiationOf(UUD, UD, Ctx);
3939 }
3940 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003941
Anders Carlsson0d8df782009-08-29 19:37:28 +00003942 return false;
3943 }
Mike Stump1eb44332009-09-09 15:08:12 +00003944
John McCall52a575a2009-08-29 08:11:13 +00003945 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3946 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003947
John McCall52a575a2009-08-29 08:11:13 +00003948 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3949 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003950
John McCall52a575a2009-08-29 08:11:13 +00003951 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3952 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003953
Douglas Gregor7caa6822009-07-24 20:34:43 +00003954 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003955 if (Var->isStaticDataMember())
3956 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3957
3958 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3959 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003960
Douglas Gregor0d696532009-09-28 06:34:35 +00003961 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3962 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3963
Douglas Gregored9c0f92009-10-29 00:04:11 +00003964 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3965 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3966 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3967 PartialSpec);
3968
Anders Carlssond8b285f2009-09-01 04:26:58 +00003969 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3970 if (!Field->getDeclName()) {
3971 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003972 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003973 cast<FieldDecl>(D);
3974 }
3975 }
Mike Stump1eb44332009-09-09 15:08:12 +00003976
John McCalled976492009-12-04 22:46:56 +00003977 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3978 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3979
3980 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3981 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3982
Douglas Gregor815215d2009-05-27 05:35:12 +00003983 return D->getDeclName() && isa<NamedDecl>(Other) &&
3984 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3985}
3986
3987template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00003988static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00003989 NamedDecl *D,
3990 ForwardIterator first,
3991 ForwardIterator last) {
3992 for (; first != last; ++first)
3993 if (isInstantiationOf(Ctx, D, *first))
3994 return cast<NamedDecl>(*first);
3995
3996 return 0;
3997}
3998
John McCall02cace72009-08-28 07:59:38 +00003999/// \brief Finds the instantiation of the given declaration context
4000/// within the current instantiation.
4001///
4002/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004003DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00004004 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00004005 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004006 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00004007 return cast_or_null<DeclContext>(ID);
4008 } else return DC;
4009}
4010
Douglas Gregored961e72009-05-27 17:54:46 +00004011/// \brief Find the instantiation of the given declaration within the
4012/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00004013///
4014/// This routine is intended to be used when \p D is a declaration
4015/// referenced from within a template, that needs to mapped into the
4016/// corresponding declaration within an instantiation. For example,
4017/// given:
4018///
4019/// \code
4020/// template<typename T>
4021/// struct X {
4022/// enum Kind {
4023/// KnownValue = sizeof(T)
4024/// };
4025///
4026/// bool getKind() const { return KnownValue; }
4027/// };
4028///
4029/// template struct X<int>;
4030/// \endcode
4031///
Serge Pavlov041d10c2013-07-10 04:59:14 +00004032/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4033/// \p EnumConstantDecl for \p KnownValue (which refers to
4034/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4035/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4036/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004037NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00004038 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00004039 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00004040 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00004041 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00004042 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4043 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004044 // D is a local of some kind. Look into the map of local
4045 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00004046 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4047 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4048 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004049
Chris Lattner57ad3782011-02-17 20:34:02 +00004050 if (Found) {
4051 if (Decl *FD = Found->dyn_cast<Decl *>())
4052 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004053
Richard Smith9a4db032012-09-12 00:56:43 +00004054 int PackIdx = ArgumentPackSubstitutionIndex;
4055 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00004056 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4057 }
4058
Serge Pavlovdc49d522013-07-15 06:14:07 +00004059 // If we're performing a partial substitution during template argument
4060 // deduction, we may not have values for template parameters yet. They
4061 // just map to themselves.
4062 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4063 isa<TemplateTemplateParmDecl>(D))
4064 return D;
4065
Chris Lattner57ad3782011-02-17 20:34:02 +00004066 // If we didn't find the decl, then we must have a label decl that hasn't
4067 // been found yet. Lazily instantiate it and return it now.
4068 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004069
Chris Lattner57ad3782011-02-17 20:34:02 +00004070 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4071 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004072
Chris Lattner57ad3782011-02-17 20:34:02 +00004073 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4074 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004075 }
Douglas Gregor815215d2009-05-27 05:35:12 +00004076
Larisse Voufoef4579c2013-08-06 01:03:05 +00004077 // For variable template specializations, update those that are still
4078 // type-dependent.
4079 if (VarTemplateSpecializationDecl *VarSpec =
4080 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4081 bool InstantiationDependent = false;
4082 const TemplateArgumentListInfo &VarTemplateArgs =
4083 VarSpec->getTemplateArgsInfo();
4084 if (TemplateSpecializationType::anyDependentTemplateArguments(
4085 VarTemplateArgs, InstantiationDependent))
4086 D = cast<NamedDecl>(
4087 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4088 return D;
4089 }
4090
Douglas Gregore95b4092009-09-16 18:34:49 +00004091 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4092 if (!Record->isDependentContext())
4093 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004094
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004095 // Determine whether this record is the "templated" declaration describing
4096 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00004097 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004098 if (ClassTemplate)
4099 ClassTemplate = ClassTemplate->getCanonicalDecl();
4100 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4101 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4102 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufoef4579c2013-08-06 01:03:05 +00004103
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004104 // Walk the current context to find either the record or an instantiation of
4105 // it.
4106 DeclContext *DC = CurContext;
4107 while (!DC->isFileContext()) {
4108 // If we're performing substitution while we're inside the template
4109 // definition, we'll find our own context. We're done.
4110 if (DC->Equals(Record))
4111 return Record;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004112
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004113 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4114 // Check whether we're in the process of instantiating a class template
4115 // specialization of the template we're mapping.
4116 if (ClassTemplateSpecializationDecl *InstSpec
4117 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4118 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4119 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4120 return InstRecord;
4121 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004122
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004123 // Check whether we're in the process of instantiating a member class.
4124 if (isInstantiationOf(Record, InstRecord))
4125 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00004126 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004127
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004128 // Move to the outer template scope.
4129 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4130 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4131 DC = FD->getLexicalDeclContext();
4132 continue;
4133 }
John McCall52a575a2009-08-29 08:11:13 +00004134 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004135
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004136 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00004137 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00004138
Douglas Gregore95b4092009-09-16 18:34:49 +00004139 // Fall through to deal with other dependent record types (e.g.,
4140 // anonymous unions in class templates).
4141 }
John McCall52a575a2009-08-29 08:11:13 +00004142
Douglas Gregore95b4092009-09-16 18:34:49 +00004143 if (!ParentDC->isDependentContext())
4144 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004145
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004146 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004147 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00004148 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Douglas Gregor815215d2009-05-27 05:35:12 +00004150 if (ParentDC != D->getDeclContext()) {
4151 // We performed some kind of instantiation in the parent context,
4152 // so now we need to look into the instantiated parent context to
4153 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004154
John McCall3cb0ebd2010-03-10 03:28:59 +00004155 // If our context used to be dependent, we may need to instantiate
4156 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004157 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00004158 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004159 if (!Spec->isDependentContext()) {
4160 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00004161 const RecordType *Tag = T->getAs<RecordType>();
4162 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004163 if (Tag->isBeingDefined())
4164 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00004165 if (!Tag->isBeingDefined() &&
4166 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4167 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00004168
4169 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004170 }
4171 }
4172
Douglas Gregor815215d2009-05-27 05:35:12 +00004173 NamedDecl *Result = 0;
4174 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004175 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00004176 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004177 } else {
4178 // Since we don't have a name for the entity we're looking for,
4179 // our only option is to walk through all of the declarations to
4180 // find that name. This will occur in a few cases:
4181 //
4182 // - anonymous struct/union within a template
4183 // - unnamed class/struct/union/enum within a template
4184 //
4185 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00004186 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004187 ParentDC->decls_begin(),
4188 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004189 }
Mike Stump1eb44332009-09-09 15:08:12 +00004190
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004191 if (!Result) {
4192 if (isa<UsingShadowDecl>(D)) {
4193 // UsingShadowDecls can instantiate to nothing because of using hiding.
4194 } else if (Diags.hasErrorOccurred()) {
4195 // We've already complained about something, so most likely this
4196 // declaration failed to instantiate. There's no point in complaining
4197 // further, since this is normal in invalid code.
4198 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004199 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004200 // instantiated, and we haven't gotten around to instantiating this
4201 // member yet. This can happen when the code uses forward declarations
4202 // of member classes, and introduces ordering dependencies via
4203 // template instantiation.
4204 Diag(Loc, diag::err_member_not_yet_instantiated)
4205 << D->getDeclName()
4206 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4207 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00004208 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4209 // This enumeration constant was found when the template was defined,
4210 // but can't be found in the instantiation. This can happen if an
4211 // unscoped enumeration member is explicitly specialized.
4212 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4213 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4214 TemplateArgs));
4215 assert(Spec->getTemplateSpecializationKind() ==
4216 TSK_ExplicitSpecialization);
4217 Diag(Loc, diag::err_enumerator_does_not_exist)
4218 << D->getDeclName()
4219 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4220 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4221 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004222 } else {
4223 // We should have found something, but didn't.
4224 llvm_unreachable("Unable to find instantiation of declaration!");
4225 }
4226 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004227
Douglas Gregor815215d2009-05-27 05:35:12 +00004228 D = Result;
4229 }
4230
Douglas Gregor815215d2009-05-27 05:35:12 +00004231 return D;
4232}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004233
Mike Stump1eb44332009-09-09 15:08:12 +00004234/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004235/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00004236void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004237 // Load pending instantiations from the external source.
4238 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00004239 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004240 ExternalSource->ReadPendingInstantiations(Pending);
4241 PendingInstantiations.insert(PendingInstantiations.begin(),
4242 Pending.begin(), Pending.end());
4243 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004244
Douglas Gregor60406be2010-01-16 22:29:39 +00004245 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00004246 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00004247 PendingImplicitInstantiation Inst;
4248
4249 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00004250 Inst = PendingInstantiations.front();
4251 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00004252 } else {
4253 Inst = PendingLocalImplicitInstantiations.front();
4254 PendingLocalImplicitInstantiations.pop_front();
4255 }
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Douglas Gregor7caa6822009-07-24 20:34:43 +00004257 // Instantiate function definitions
4258 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00004259 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4260 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004261 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4262 TSK_ExplicitInstantiationDefinition;
4263 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4264 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00004265 continue;
4266 }
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Larisse Voufoef4579c2013-08-06 01:03:05 +00004268 // Instantiate variable definitions
Douglas Gregor7caa6822009-07-24 20:34:43 +00004269 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufoef4579c2013-08-06 01:03:05 +00004270
4271 assert((Var->isStaticDataMember() ||
4272 isa<VarTemplateSpecializationDecl>(Var)) &&
4273 "Not a static data member, nor a variable template"
4274 " specialization?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00004275
Chandler Carruth291b4412010-02-13 10:17:50 +00004276 // Don't try to instantiate declarations if the most recent redeclaration
4277 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004278 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00004279 continue;
4280
4281 // Check if the most recent declaration has changed the specialization kind
4282 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004283 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00004284 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00004285 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00004286 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00004287 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00004288 continue; // No longer need to instantiate this type.
4289 case TSK_ExplicitInstantiationDefinition:
4290 // We only need an instantiation if the pending instantiation *is* the
4291 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004292 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00004293 case TSK_ImplicitInstantiation:
4294 break;
4295 }
4296
Larisse Voufoef4579c2013-08-06 01:03:05 +00004297 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4298 "instantiating variable definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004299 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4300 TSK_ExplicitInstantiationDefinition;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004301
4302 // Instantiate static data member definitions or variable template
4303 // specializations.
4304 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4305 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004306 }
4307}
John McCall0c01d182010-03-24 05:22:00 +00004308
4309void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4310 const MultiLevelTemplateArgumentList &TemplateArgs) {
4311 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4312 E = Pattern->ddiag_end(); I != E; ++I) {
4313 DependentDiagnostic *DD = *I;
4314
4315 switch (DD->getKind()) {
4316 case DependentDiagnostic::Access:
4317 HandleDependentAccessCheck(*DD, TemplateArgs);
4318 break;
4319 }
4320 }
4321}